@myrialabs/clopen 0.4.17 → 0.4.19

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 (91) 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/opencode/server.ts +2 -1
  32. package/backend/engine/adapters/pi/presets.ts +3 -1
  33. package/backend/engine/adapters/pi/session-fork.ts +3 -1
  34. package/backend/engine/adapters/pi/stream.ts +11 -8
  35. package/backend/engine/adapters/qwen/stream.ts +10 -8
  36. package/backend/engine/bootstrap-default-engine.ts +69 -0
  37. package/backend/engine/docs/adding-an-engine.md +29 -6
  38. package/backend/engine/docs/frontend-and-chat.md +21 -5
  39. package/backend/engine/docs/lessons-learned.md +41 -0
  40. package/backend/engine/docs/quick-reference.md +3 -2
  41. package/backend/engine/docs/system-tools.md +65 -9
  42. package/backend/engine/docs/websocket-routes.md +4 -3
  43. package/backend/engine/engine-setup.ts +72 -0
  44. package/backend/engine/install-recipes.ts +82 -77
  45. package/backend/engine/install-runner.ts +27 -2
  46. package/backend/engine/sdk-loader.ts +180 -0
  47. package/backend/engine/version-check.ts +6 -6
  48. package/backend/http/files-upload.test.ts +4 -1
  49. package/backend/index.ts +32 -2
  50. package/backend/mcp/README.md +26 -8
  51. package/backend/mcp/index.ts +2 -2
  52. package/backend/mcp/internal/config.ts +54 -63
  53. package/backend/mcp/internal/remote-server.test.ts +4 -1
  54. package/backend/mcp/internal/servers/helper.ts +4 -34
  55. package/backend/mcp/internal/servers/index.ts +4 -13
  56. package/backend/tunnel/public-origin.ts +118 -0
  57. package/backend/utils/ws.ts +126 -1
  58. package/backend/ws/auth/device.ts +239 -0
  59. package/backend/ws/auth/index.ts +8 -0
  60. package/backend/ws/auth/invites.ts +16 -6
  61. package/backend/ws/auth/login.test.ts +2 -2
  62. package/backend/ws/auth/login.ts +12 -6
  63. package/backend/ws/engine/claude/status.ts +4 -4
  64. package/backend/ws/engine/cline/accounts.ts +3 -2
  65. package/backend/ws/engine/cline/status.ts +4 -12
  66. package/backend/ws/engine/codex/status.ts +4 -12
  67. package/backend/ws/engine/copilot/status.ts +5 -12
  68. package/backend/ws/engine/cursor/accounts.ts +2 -1
  69. package/backend/ws/engine/cursor/status.ts +5 -12
  70. package/backend/ws/engine/opencode/status.ts +4 -4
  71. package/backend/ws/engine/pi/status.ts +4 -12
  72. package/backend/ws/engine/qwen/status.ts +5 -12
  73. package/backend/ws/sessions/crud.ts +29 -4
  74. package/backend/ws/settings/crud.ts +10 -1
  75. package/backend/ws/system/operations.ts +34 -18
  76. package/backend/ws/system-tools/install.ts +3 -0
  77. package/backend/ws/system-tools/status.ts +7 -2
  78. package/backend/ws/tunnel/index.ts +3 -1
  79. package/backend/ws/tunnel/share.ts +27 -0
  80. package/bin/clopen.ts +1 -1
  81. package/dist/assets/{index-kME3THy5.js → index-BqBxKeAv.js} +1 -1
  82. package/dist/assets/{index-Bu5loFQE.js → index-DdrcY5TE.js} +1 -1
  83. package/dist/assets/{main-HirJLquI.js → main-BBxAj17T.js} +337 -330
  84. package/dist/assets/main-Cry3pLcl.css +1 -0
  85. package/dist/index.html +2 -2
  86. package/package.json +15 -14
  87. package/shared/constants/engines.ts +39 -40
  88. package/shared/constants/tool-icons.ts +49 -0
  89. package/shared/types/stores/settings.ts +9 -0
  90. package/shared/utils/logger.ts +1 -0
  91. package/dist/assets/main-D7ATW8pp.css +0 -1
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Public origin resolution for Remote Access.
3
+ *
4
+ * "Make this Clopen reachable from another device" needs a public origin to
5
+ * build share links against. Where that origin comes from is adaptive, so the
6
+ * caller never has to think about tunnels vs domains:
7
+ *
8
+ * 1. `configured` — an admin-set public URL (system setting `publicBaseUrl`),
9
+ * for VPS/reverse-proxy deployments where the browser can't see the real
10
+ * hostname.
11
+ * 2. `domain` — the browser is already hitting Clopen on a non-local origin
12
+ * (a real deployment), so reuse that origin directly. No tunnel needed.
13
+ * 3. `tunnel` — local install: start (or reuse) a Cloudflare quick tunnel to
14
+ * Clopen's own server port and use its `*.trycloudflare.com` URL.
15
+ */
16
+
17
+ import { tunnelKit, portFromService } from './tunnel-config';
18
+ import { SERVER_ENV } from '../utils/env';
19
+ import { settingsQueries } from '$backend/database/queries';
20
+ import { debug } from '$shared/utils/logger';
21
+
22
+ export type PublicOriginSource = 'configured' | 'domain' | 'tunnel';
23
+
24
+ export interface PublicOrigin {
25
+ /** Absolute origin, no trailing slash (e.g. https://foo.trycloudflare.com). */
26
+ origin: string;
27
+ source: PublicOriginSource;
28
+ }
29
+
30
+ /** Hostnames that are not reachable by another device — force a tunnel. */
31
+ function isLocalHostname(hostname: string): boolean {
32
+ const h = hostname.toLowerCase();
33
+ if (h === 'localhost' || h.endsWith('.localhost')) return true;
34
+ if (h === '127.0.0.1' || h === '::1' || h === '0.0.0.0') return true;
35
+ // Private LAN ranges (RFC1918 + link-local + CGNAT).
36
+ if (/^10\./.test(h)) return true;
37
+ if (/^192\.168\./.test(h)) return true;
38
+ if (/^172\.(1[6-9]|2\d|3[01])\./.test(h)) return true;
39
+ if (/^169\.254\./.test(h)) return true;
40
+ if (/^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./.test(h)) return true;
41
+ // `.local` mDNS names resolve on-LAN only.
42
+ if (h.endsWith('.local')) return true;
43
+ return false;
44
+ }
45
+
46
+ /** Strip a trailing slash so callers can append `/#invite/...` cleanly. */
47
+ function normalizeOrigin(url: string): string {
48
+ return url.replace(/\/+$/, '');
49
+ }
50
+
51
+ /** Read the admin-configured public base URL from system settings, if any. */
52
+ function getConfiguredPublicBaseUrl(): string | null {
53
+ try {
54
+ const setting = settingsQueries.get('system:settings');
55
+ if (!setting?.value) return null;
56
+ const parsed = typeof setting.value === 'string' ? JSON.parse(setting.value) : setting.value;
57
+ const url = parsed?.publicBaseUrl;
58
+ if (typeof url === 'string' && url.trim()) {
59
+ return normalizeOrigin(url.trim());
60
+ }
61
+ } catch {
62
+ // Settings may not exist yet.
63
+ }
64
+ return null;
65
+ }
66
+
67
+ /** Find an already-running quick tunnel pointing at the given local port. */
68
+ function findQuickTunnelForPort(port: number): string | null {
69
+ for (const t of tunnelKit.list()) {
70
+ if (t.type === 'quick' && portFromService(t.service) === port && t.publicUrl) {
71
+ return normalizeOrigin(t.publicUrl);
72
+ }
73
+ }
74
+ return null;
75
+ }
76
+
77
+ /**
78
+ * Resolve a public origin for Remote Access share links. `requestOrigin` is the
79
+ * browser's own `window.location.origin` (passed by the client), used to detect
80
+ * the already-public `domain` case.
81
+ */
82
+ export async function resolvePublicOrigin(requestOrigin?: string): Promise<PublicOrigin> {
83
+ // 1. Explicitly configured public URL wins.
84
+ const configured = getConfiguredPublicBaseUrl();
85
+ if (configured) {
86
+ return { origin: configured, source: 'configured' };
87
+ }
88
+
89
+ // 2. Already served on a real (non-local) origin — reuse it.
90
+ if (requestOrigin) {
91
+ try {
92
+ const url = new URL(requestOrigin);
93
+ if (!isLocalHostname(url.hostname)) {
94
+ return { origin: normalizeOrigin(requestOrigin), source: 'domain' };
95
+ }
96
+ } catch {
97
+ // Malformed origin — fall through to tunnel.
98
+ }
99
+ }
100
+
101
+ // 3. Local install — tunnel Clopen's own port. In dev the app is served by
102
+ // Vite on PORT_FRONTEND (which proxies to the backend), so tunnel that; in
103
+ // production frontend and backend share PORT.
104
+ const port = SERVER_ENV.isDevelopment ? SERVER_ENV.PORT_FRONTEND : SERVER_ENV.PORT;
105
+
106
+ const existing = findQuickTunnelForPort(port);
107
+ if (existing) {
108
+ return { origin: existing, source: 'tunnel' };
109
+ }
110
+
111
+ debug.log('tunnel', `[remote-access] Starting quick tunnel for Clopen port ${port}`);
112
+ await tunnelKit.bin.ensure();
113
+ const { publicUrl } = await tunnelKit.quick.start({ service: port, autoStopMinutes: 0 });
114
+ if (!publicUrl) {
115
+ throw new Error('Failed to establish a public tunnel');
116
+ }
117
+ return { origin: normalizeOrigin(publicUrl), source: 'tunnel' };
118
+ }
@@ -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);