@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
package/README.md CHANGED
@@ -69,7 +69,7 @@ A complete development environment designed around AI-assisted workflows, built
69
69
  - **Connectors (MCP)** — Browse a searchable catalog of Model Context Protocol servers, connect with OAuth or custom env/headers, and sync every connector across all your AI engines
70
70
  - **Skills, Commands & Subagents** — Build reusable Skills, slash Commands, delegated Subagents, shared Instructions, and tool Permissions or Profiles once, synced automatically across every engine
71
71
  - **Flexible Authentication** — No Login or With Login mode with admin/member roles, invite links, rate-limited login, and CLI token recovery
72
- - **System Tools Installer** — Install Git, Claude Code, OpenCode, Codex, Copilot, Qwen Code, Chrome, and Cloudflared (for Public Tunnel) from a one-click admin panel
72
+ - **Stack** — Install AI engines, Git, Chrome, and Cloudflared (for Public Tunnel) from a one-click admin panel. Engines install on demand into a clopen-managed directory (`~/.clopen/stack/engines`) — isolated from your global setup, no PATH pollution
73
73
  - **Background Processing** — Chat, terminal, and other processes continue running even when you close the browser — come back later and pick up where you left off
74
74
  - **Works on Any Device** — Fully responsive across desktop, laptop, tablet, and mobile. Open your workspace from any device and continue exactly where you left off
75
75
 
@@ -80,7 +80,7 @@ A complete development environment designed around AI-assisted workflows, built
80
80
  ### Prerequisites
81
81
 
82
82
  - [Bun.js](https://bun.sh/) v1.2.12+
83
- - At least one supported AI engine — [Claude Code](https://github.com/anthropics/claude-code), [OpenCode](https://opencode.ai), [Codex](https://github.com/openai/codex), [GitHub Copilot CLI](https://github.com/github/copilot-cli), or [Qwen Code](https://github.com/QwenLM/qwen-code). All are installable from **Settings → System Tools** after first launch. [Pi](https://github.com/earendil-works/pi), [Cline](https://github.com/cline/cline), and [Cursor](https://cursor.com) are bundled as in-process SDKs and need no separate CLI install — just sign in from **Settings → Engines**
83
+ - At least one supported AI engine — [Claude Code](https://github.com/anthropics/claude-code), [OpenCode](https://opencode.ai), [Codex](https://github.com/openai/codex), [GitHub Copilot CLI](https://github.com/github/copilot-cli), [Qwen Code](https://github.com/QwenLM/qwen-code), [Pi](https://github.com/earendil-works/pi), [Cline](https://github.com/cline/cline), or [Cursor](https://cursor.com). All install on demand from **Settings → Stack** after first launch (nothing is bundled into the clopen install), then sign in from **Settings → Engines**
84
84
 
85
85
  ### Installation
86
86
 
@@ -116,7 +116,7 @@ On first launch, a setup wizard guides you through:
116
116
 
117
117
  1. **Authentication mode** — Choose between **No Login** (no authentication required, ideal for personal/local use) or **With Login** (login with Personal Access Token, supports team collaboration)
118
118
  2. **Admin account** — If With Login mode is selected, create your admin account and save the generated PAT
119
- 3. **System Tools** — Install Git, Chrome, Cloudflared, and any AI engine you don't have yet — straight from the wizard, no terminal needed
119
+ 3. **Stack** — Install Git, Chrome, Cloudflared, and any AI engine you don't have yet — straight from the wizard, no terminal needed
120
120
  4. **AI Engines** — Check installation status for Claude Code, OpenCode, Codex, Copilot, and Qwen Code, and sign in to the engines you'll use. Pi, Cline, and Cursor need no install and are ready to sign in to directly
121
121
  5. **Preferences** — Set dark mode, font size, sound notifications, and message layout (Classic cards or Compact lines)
122
122
 
@@ -6,13 +6,16 @@
6
6
 
7
7
  import { authQueries, projectQueries, settingsQueries } from '$backend/database/queries';
8
8
  import type { Project } from '$shared/types/database/schema';
9
- import { generateSessionToken, generatePAT, generateInviteToken, hashToken, getTokenType } from './tokens';
9
+ import { generateSessionToken, generatePAT, generateInviteToken, generateDeviceCode, hashToken, getTokenType } from './tokens';
10
10
  import { generateColorFromString, getInitials } from '$backend/utils/user-helpers';
11
11
  import { debug } from '$shared/utils/logger';
12
12
 
13
13
  /** Default session lifetime in days */
14
14
  const DEFAULT_SESSION_DAYS = 30;
15
15
 
16
+ /** How long a device-pairing code stays claimable before it expires (minutes). */
17
+ const DEVICE_CODE_TTL_MINUTES = 5;
18
+
16
19
  export interface AuthUser {
17
20
  id: string;
18
21
  name: string;
@@ -43,7 +46,16 @@ function toAuthUser(dbUser: { id: string; name: string; color: string; avatar: s
43
46
  };
44
47
  }
45
48
 
46
- function createSessionForUser(userId: string, sessionDays?: number): { sessionToken: string; expiresAt: string; tokenHash: string } {
49
+ /** Optional device metadata captured when a session is created (UA client-sent, IP server-side). */
50
+ export interface SessionMeta {
51
+ userAgent?: string;
52
+ ipAddress?: string;
53
+ }
54
+
55
+ /** How a session was created — surfaced in the admin "Connected devices" view. */
56
+ export type SessionSource = 'setup' | 'invite' | 'device-link' | 'login' | 'pat' | 'no-auth';
57
+
58
+ function createSessionForUser(userId: string, source: SessionSource, meta?: SessionMeta, sessionDays?: number): { sessionToken: string; expiresAt: string; tokenHash: string } {
47
59
  const days = sessionDays ?? DEFAULT_SESSION_DAYS;
48
60
  const sessionToken = generateSessionToken();
49
61
  const tokenHash = hashToken(sessionToken);
@@ -56,7 +68,10 @@ function createSessionForUser(userId: string, sessionDays?: number): { sessionTo
56
68
  token_hash: tokenHash,
57
69
  expires_at: expiresAt,
58
70
  created_at: now,
59
- last_active_at: now
71
+ last_active_at: now,
72
+ user_agent: meta?.userAgent?.slice(0, 512) ?? null,
73
+ ip_address: meta?.ipAddress ?? null,
74
+ source
60
75
  });
61
76
 
62
77
  return { sessionToken, expiresAt, tokenHash };
@@ -114,7 +129,7 @@ export function createOrGetNoAuthAdmin(): AuthResult {
114
129
  const existingUsers = authQueries.getAllUsers();
115
130
  const existingAdmin = existingUsers.find(u => u.role === 'admin');
116
131
  if (existingAdmin) {
117
- const { sessionToken, expiresAt } = createSessionForUser(existingAdmin.id);
132
+ const { sessionToken, expiresAt } = createSessionForUser(existingAdmin.id, 'no-auth');
118
133
  debug.log('auth', `No-auth mode: reusing existing admin: ${existingAdmin.name} (${existingAdmin.id})`);
119
134
  return {
120
135
  user: toAuthUser(existingAdmin),
@@ -138,7 +153,7 @@ export function createOrGetNoAuthAdmin(): AuthResult {
138
153
  created_at: now
139
154
  });
140
155
 
141
- const { sessionToken, expiresAt } = createSessionForUser(userId);
156
+ const { sessionToken, expiresAt } = createSessionForUser(userId, 'no-auth');
142
157
 
143
158
  debug.log('auth', `No-auth mode: created default admin: ${defaultName} (${userId})`);
144
159
 
@@ -153,7 +168,7 @@ export function createOrGetNoAuthAdmin(): AuthResult {
153
168
  * Create the first admin user (setup flow)
154
169
  * Only works when no users exist.
155
170
  */
156
- export function createAdmin(name: string): SetupResult {
171
+ export function createAdmin(name: string, meta?: SessionMeta): SetupResult {
157
172
  if (!needsSetup()) {
158
173
  throw new Error('Setup already completed. Admin account exists.');
159
174
  }
@@ -178,7 +193,7 @@ export function createAdmin(name: string): SetupResult {
178
193
  created_at: now
179
194
  });
180
195
 
181
- const { sessionToken, expiresAt } = createSessionForUser(userId);
196
+ const { sessionToken, expiresAt } = createSessionForUser(userId, 'setup', meta);
182
197
 
183
198
  debug.log('auth', `Admin account created: ${trimmedName} (${userId})`);
184
199
 
@@ -193,7 +208,7 @@ export function createAdmin(name: string): SetupResult {
193
208
  /**
194
209
  * Create a user from an invite token
195
210
  */
196
- export function createUserFromInvite(rawInviteToken: string, name: string): SetupResult {
211
+ export function createUserFromInvite(rawInviteToken: string, name: string, meta?: SessionMeta): SetupResult {
197
212
  const trimmedName = name.trim();
198
213
  if (trimmedName.length === 0) {
199
214
  throw new Error('Name cannot be empty');
@@ -237,7 +252,22 @@ export function createUserFromInvite(rawInviteToken: string, name: string): Setu
237
252
  // Increment invite use count
238
253
  authQueries.incrementUseCount(invite.id);
239
254
 
240
- const { sessionToken, expiresAt } = createSessionForUser(userId);
255
+ // Apply any projects the admin pre-selected when creating the invite, so the
256
+ // new member has access the moment they join (no separate assignment trip).
257
+ if (invite.project_ids) {
258
+ try {
259
+ const projectIds: string[] = JSON.parse(invite.project_ids);
260
+ for (const projectId of projectIds) {
261
+ if (projectQueries.getById(projectId) && !projectQueries.userHasProject(userId, projectId)) {
262
+ projectQueries.addUserProject(userId, projectId);
263
+ }
264
+ }
265
+ } catch (err) {
266
+ debug.warn('auth', 'Failed to apply invite project pre-assignment:', err);
267
+ }
268
+ }
269
+
270
+ const { sessionToken, expiresAt } = createSessionForUser(userId, 'invite', meta);
241
271
 
242
272
  debug.log('auth', `User created from invite: ${trimmedName} (${userId}), role: ${role}`);
243
273
 
@@ -252,7 +282,7 @@ export function createUserFromInvite(rawInviteToken: string, name: string): Setu
252
282
  /**
253
283
  * Login with a token (PAT or session token)
254
284
  */
255
- export function loginWithToken(token: string): AuthResult & { tokenHash: string } {
285
+ export function loginWithToken(token: string, meta?: SessionMeta): AuthResult & { tokenHash: string } {
256
286
  const tokenType = getTokenType(token);
257
287
  const tokenHash = hashToken(token);
258
288
 
@@ -263,7 +293,7 @@ export function loginWithToken(token: string): AuthResult & { tokenHash: string
263
293
  throw new Error('Invalid access token');
264
294
  }
265
295
 
266
- const session = createSessionForUser(user.id);
296
+ const session = createSessionForUser(user.id, 'pat', meta);
267
297
  debug.log('auth', `PAT login: ${user.name} (${user.id})`);
268
298
 
269
299
  return {
@@ -358,7 +388,7 @@ export function removeUser(userId: string): void {
358
388
  */
359
389
  export function createInvite(
360
390
  createdBy: string,
361
- options: { label?: string; maxUses?: number; expiresInMinutes?: number }
391
+ options: { label?: string; maxUses?: number; expiresInMinutes?: number; projectIds?: string[] }
362
392
  ): { inviteToken: string; invite: ReturnType<typeof authQueries.getInviteByTokenHash> } {
363
393
  const rawToken = generateInviteToken();
364
394
  const tokenHash = hashToken(rawToken);
@@ -368,6 +398,9 @@ export function createInvite(
368
398
  ? new Date(Date.now() + options.expiresInMinutes * 60 * 1000).toISOString()
369
399
  : null;
370
400
 
401
+ // Keep only project ids that actually exist so a stale pick can't wedge the join.
402
+ const validProjectIds = (options.projectIds ?? []).filter((id) => projectQueries.getById(id));
403
+
371
404
  const invite = authQueries.createInvite({
372
405
  id: `invite-${crypto.randomUUID()}`,
373
406
  token_hash: tokenHash,
@@ -377,7 +410,8 @@ export function createInvite(
377
410
  max_uses: options.maxUses ?? 1,
378
411
  use_count: 0,
379
412
  expires_at: expiresAt,
380
- created_at: now
413
+ created_at: now,
414
+ project_ids: validProjectIds.length ? JSON.stringify(validProjectIds) : null
381
415
  });
382
416
 
383
417
  debug.log('auth', `Invite created by ${createdBy}: ${invite.id}`);
@@ -441,6 +475,101 @@ export function regeneratePAT(userId: string): string {
441
475
  return pat;
442
476
  }
443
477
 
478
+ /**
479
+ * Create a one-time device-pairing code for the given user. The code is a
480
+ * random `clp_dev_*` token; only its hash is stored. Embed the raw code in a
481
+ * Remote Access share link so another device can claim it and sign in as this
482
+ * user without transferring a persistent credential.
483
+ */
484
+ export function createDeviceCode(userId: string, label?: string): { deviceCode: string; expiresAt: string } {
485
+ const user = authQueries.getUserById(userId);
486
+ if (!user) {
487
+ throw new Error('User not found');
488
+ }
489
+
490
+ const rawCode = generateDeviceCode();
491
+ const codeHash = hashToken(rawCode);
492
+ const now = new Date().toISOString();
493
+ const expiresAt = new Date(Date.now() + DEVICE_CODE_TTL_MINUTES * 60 * 1000).toISOString();
494
+
495
+ authQueries.createDeviceCode({
496
+ id: `device-${crypto.randomUUID()}`,
497
+ code_hash: codeHash,
498
+ user_id: userId,
499
+ label: label?.trim() || null,
500
+ expires_at: expiresAt,
501
+ claimed_at: null,
502
+ created_at: now
503
+ });
504
+
505
+ debug.log('auth', `Device code created for user: ${user.name} (${userId})`);
506
+
507
+ return { deviceCode: rawCode, expiresAt };
508
+ }
509
+
510
+ /**
511
+ * Claim a device-pairing code — single-use. Validates the code is unexpired and
512
+ * unclaimed, burns it, and issues a fresh auth session for the owning user.
513
+ */
514
+ export function claimDeviceCode(rawCode: string, meta?: SessionMeta): AuthResult & { tokenHash: string } {
515
+ if (getTokenType(rawCode) !== 'device') {
516
+ throw new Error('Invalid device code');
517
+ }
518
+
519
+ const codeHash = hashToken(rawCode);
520
+ const record = authQueries.getDeviceCodeByHash(codeHash);
521
+
522
+ if (!record) {
523
+ throw new Error('Invalid device code');
524
+ }
525
+
526
+ if (record.claimed_at) {
527
+ throw new Error('This device code has already been used');
528
+ }
529
+
530
+ if (new Date(record.expires_at) < new Date()) {
531
+ authQueries.deleteDeviceCode(record.id);
532
+ throw new Error('This device code has expired');
533
+ }
534
+
535
+ // Burn the code atomically — if another claim won the race, changes === 0.
536
+ const claimed = authQueries.markDeviceCodeClaimed(record.id, new Date().toISOString());
537
+ if (claimed === 0) {
538
+ throw new Error('This device code has already been used');
539
+ }
540
+
541
+ const user = authQueries.getUserById(record.user_id);
542
+ if (!user) {
543
+ authQueries.deleteDeviceCode(record.id);
544
+ throw new Error('Invalid device code');
545
+ }
546
+
547
+ const session = createSessionForUser(user.id, 'device-link', meta);
548
+ debug.log('auth', `Device code claimed: ${user.name} (${user.id})`);
549
+
550
+ return {
551
+ user: toAuthUser(user),
552
+ sessionToken: session.sessionToken,
553
+ expiresAt: session.expiresAt,
554
+ tokenHash: session.tokenHash
555
+ };
556
+ }
557
+
558
+ /**
559
+ * Revoke an unclaimed device code (owner-scoped). Used when a new link replaces
560
+ * an old one so the previous QR/code stops working immediately.
561
+ */
562
+ export function revokeDeviceCode(userId: string, rawCode: string): boolean {
563
+ const hash = hashToken(rawCode);
564
+ const record = authQueries.getDeviceCodeByHash(hash);
565
+ if (!record || record.user_id !== userId) {
566
+ return false;
567
+ }
568
+ authQueries.deleteDeviceCode(record.id);
569
+ debug.log('auth', `Device code revoked (user ${userId})`);
570
+ return true;
571
+ }
572
+
444
573
  /**
445
574
  * Update user display name
446
575
  */
@@ -527,6 +656,124 @@ export function unassignProjectFromUser(userId: string, projectId: string): bool
527
656
  return true;
528
657
  }
529
658
 
659
+ /**
660
+ * List a user's active auth sessions (devices). `current` marks the session
661
+ * matching the given token hash so the caller can flag "this device".
662
+ */
663
+ export interface AuthSessionInfo {
664
+ id: string;
665
+ createdAt: string;
666
+ lastActiveAt: string;
667
+ expiresAt: string;
668
+ current: boolean;
669
+ /** True when a live WS connection is currently bound to this session. */
670
+ online: boolean;
671
+ userAgent: string | null;
672
+ ipAddress: string | null;
673
+ source: string | null;
674
+ }
675
+
676
+ /** Admin "Connected devices" row — a session enriched with its owning user. */
677
+ export interface AdminSessionInfo extends AuthSessionInfo {
678
+ userId: string;
679
+ userName: string;
680
+ userColor: string;
681
+ userRole: 'admin' | 'member';
682
+ }
683
+
684
+ export function listUserSessions(userId: string, currentTokenHash?: string, onlineHashes?: Set<string>): AuthSessionInfo[] {
685
+ return authQueries.getSessionsByUserId(userId).map((s) => ({
686
+ id: s.id,
687
+ createdAt: s.created_at,
688
+ lastActiveAt: s.last_active_at,
689
+ expiresAt: s.expires_at,
690
+ current: currentTokenHash !== undefined && s.token_hash === currentTokenHash,
691
+ online: onlineHashes?.has(s.token_hash) ?? false,
692
+ userAgent: s.user_agent,
693
+ ipAddress: s.ip_address,
694
+ source: s.source
695
+ }));
696
+ }
697
+
698
+ /**
699
+ * List every session across all users (admin view), enriched with the owning
700
+ * user's identity and whether the device is currently online.
701
+ */
702
+ export function listAllSessions(currentTokenHash?: string, onlineHashes?: Set<string>): AdminSessionInfo[] {
703
+ return authQueries.getAllSessions().map((s) => {
704
+ const user = authQueries.getUserById(s.user_id);
705
+ return {
706
+ id: s.id,
707
+ createdAt: s.created_at,
708
+ lastActiveAt: s.last_active_at,
709
+ expiresAt: s.expires_at,
710
+ current: currentTokenHash !== undefined && s.token_hash === currentTokenHash,
711
+ online: onlineHashes?.has(s.token_hash) ?? false,
712
+ userAgent: s.user_agent,
713
+ ipAddress: s.ip_address,
714
+ source: s.source,
715
+ userId: s.user_id,
716
+ userName: user?.name ?? 'Unknown',
717
+ userColor: user?.color ?? '#888888',
718
+ userRole: user?.role ?? 'member'
719
+ };
720
+ });
721
+ }
722
+
723
+ /**
724
+ * Revoke one of a user's own sessions by id. Scoped to the owner so a member
725
+ * can only sign out their own devices. Returns the deleted session's token hash
726
+ * so the caller can kick any live WS connection bound to it.
727
+ */
728
+ export function revokeUserSession(userId: string, sessionId: string): { success: boolean; tokenHash?: string } {
729
+ const session = authQueries.getSessionById(sessionId);
730
+ if (!session || session.user_id !== userId) {
731
+ return { success: false };
732
+ }
733
+ authQueries.deleteSession(sessionId);
734
+ debug.log('auth', `Session revoked: ${sessionId} (user ${userId})`);
735
+ return { success: true, tokenHash: session.token_hash };
736
+ }
737
+
738
+ /**
739
+ * Revoke any session by id (admin-only). Unlike revokeUserSession this is not
740
+ * owner-scoped — an admin can sign out any connected device. Returns the token
741
+ * hash so the caller can kick the live WS connection immediately.
742
+ */
743
+ export function revokeAnySession(sessionId: string): { success: boolean; tokenHash?: string } {
744
+ const session = authQueries.getSessionById(sessionId);
745
+ if (!session) {
746
+ return { success: false };
747
+ }
748
+ authQueries.deleteSession(sessionId);
749
+ debug.log('auth', `Session revoked by admin: ${sessionId} (user ${session.user_id})`);
750
+ return { success: true, tokenHash: session.token_hash };
751
+ }
752
+
753
+ /**
754
+ * Remote Access sidebar indicator: the number of *other* devices currently
755
+ * online. "Active" means a live WS connection is bound to the session right now
756
+ * — not merely a session row in the DB — so this mirrors Public Tunnel's live
757
+ * connection count and the "Connected devices" list. A member sees their own
758
+ * online devices; an admin sees the whole team's. The viewer's current device
759
+ * is always excluded so the badge reads "N remote devices connected".
760
+ */
761
+ export function getRemoteAccessSummary(
762
+ userId: string,
763
+ isAdmin: boolean,
764
+ onlineHashes: Set<string>,
765
+ currentTokenHash?: string
766
+ ): { activeConnections: number } {
767
+ const sessions = isAdmin ? authQueries.getAllSessions() : authQueries.getSessionsByUserId(userId);
768
+ let activeConnections = 0;
769
+ for (const s of sessions) {
770
+ if (!onlineHashes.has(s.token_hash)) continue;
771
+ if (currentTokenHash && s.token_hash === currentTokenHash) continue;
772
+ activeConnections++;
773
+ }
774
+ return { activeConnections };
775
+ }
776
+
530
777
  /**
531
778
  * Cleanup expired sessions
532
779
  */
@@ -535,5 +782,10 @@ export function cleanupExpiredSessions(): number {
535
782
  if (count > 0) {
536
783
  debug.log('auth', `Cleaned up ${count} expired sessions`);
537
784
  }
785
+ // Also sweep expired / already-claimed device codes.
786
+ const staleCodes = authQueries.deleteStaleDeviceCodes();
787
+ if (staleCodes > 0) {
788
+ debug.log('auth', `Cleaned up ${staleCodes} stale device code(s)`);
789
+ }
538
790
  return count;
539
791
  }
@@ -16,6 +16,7 @@ export const PUBLIC_ROUTES = new Set([
16
16
  'auth:auto-login-no-auth',
17
17
  'auth:accept-invite',
18
18
  'auth:validate-invite',
19
+ 'auth:claim-device-code',
19
20
  'ws:set-context'
20
21
  ]);
21
22
 
@@ -26,6 +27,8 @@ export const ADMIN_ONLY_ROUTES = new Set([
26
27
  'auth:create-invite',
27
28
  'auth:list-invites',
28
29
  'auth:revoke-invite',
30
+ 'auth:list-all-sessions',
31
+ 'auth:revoke-any-session',
29
32
  'auth:list-users',
30
33
  'auth:remove-user',
31
34
  'auth:list-user-projects',
@@ -19,6 +19,7 @@ const RATE_LIMITED_ROUTES = new Set([
19
19
  'auth:login',
20
20
  'auth:accept-invite',
21
21
  'auth:validate-invite',
22
+ 'auth:claim-device-code',
22
23
  'auth:setup'
23
24
  ]);
24
25
 
@@ -38,6 +38,11 @@ class SessionCleanupScheduler {
38
38
  if (deleted > 0) {
39
39
  debug.log('auth', `Session cleanup: removed ${deleted} expired session(s)`);
40
40
  }
41
+ // Sweep expired / already-claimed device-pairing codes alongside sessions.
42
+ const staleCodes = authQueries.deleteStaleDeviceCodes();
43
+ if (staleCodes > 0) {
44
+ debug.log('auth', `Session cleanup: removed ${staleCodes} stale device code(s)`);
45
+ }
41
46
  } catch (error) {
42
47
  debug.warn('auth', 'Session cleanup failed:', error);
43
48
  }
@@ -5,11 +5,13 @@
5
5
  * - clp_ses_* — Session tokens (login sessions, 30 day expiry)
6
6
  * - clp_pat_* — Personal Access Tokens (cross-device login, permanent)
7
7
  * - clp_inv_* — Invite tokens (for inviting new users)
8
+ * - clp_dev_* — Device-pairing codes (one-time, short TTL; Remote Access "Add a device")
8
9
  */
9
10
 
10
11
  const SESSION_PREFIX = 'clp_ses_';
11
12
  const PAT_PREFIX = 'clp_pat_';
12
13
  const INVITE_PREFIX = 'clp_inv_';
14
+ const DEVICE_PREFIX = 'clp_dev_';
13
15
 
14
16
  function randomHex(bytes: number): string {
15
17
  const arr = new Uint8Array(bytes);
@@ -32,6 +34,10 @@ export function generateInviteToken(): string {
32
34
  return INVITE_PREFIX + randomHex(TOKEN_BYTES);
33
35
  }
34
36
 
37
+ export function generateDeviceCode(): string {
38
+ return DEVICE_PREFIX + randomHex(TOKEN_BYTES);
39
+ }
40
+
35
41
  /**
36
42
  * SHA-256 hash a token string.
37
43
  * Uses Bun native CryptoHasher for performance.
@@ -45,9 +51,10 @@ export function hashToken(token: string): string {
45
51
  /**
46
52
  * Determine token type from prefix
47
53
  */
48
- export function getTokenType(token: string): 'session' | 'pat' | 'invite' | 'unknown' {
54
+ export function getTokenType(token: string): 'session' | 'pat' | 'invite' | 'device' | 'unknown' {
49
55
  if (token.startsWith(SESSION_PREFIX)) return 'session';
50
56
  if (token.startsWith(PAT_PREFIX)) return 'pat';
51
57
  if (token.startsWith(INVITE_PREFIX)) return 'invite';
58
+ if (token.startsWith(DEVICE_PREFIX)) return 'device';
52
59
  return 'unknown';
53
60
  }
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { EventEmitter } from 'events';
12
+ import { checkEngineSetup } from '../engine/engine-setup';
12
13
  import type {
13
14
  EngineOutput,
14
15
  UnifiedMessage,
@@ -627,6 +628,13 @@ class StreamManager extends EventEmitter {
627
628
  debug.warn('chat', 'MCP OAuth refresh failed:', error)
628
629
  );
629
630
 
631
+ // Refuse to stream an engine that isn't ready and point the user at the
632
+ // exact fix (Stack to install/update, Engines to sign in). Thrown here
633
+ // so the processStream catch surfaces it as a chat error, which the
634
+ // ErrorMessage renderer turns into a one-click action.
635
+ const setupIssue = checkEngineSetup(requestEngine.type, requestEngine.account.id);
636
+ if (setupIssue) throw new Error(setupIssue.message);
637
+
630
638
  // Stream EngineOutput events through the engine adapter
631
639
  const streamIterable = engine.streamQuery({
632
640
  projectPath,
@@ -0,0 +1,38 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create device_codes table for one-time device-pairing sign-in (Remote Access)';
5
+
6
+ /**
7
+ * Device codes back the "Add a device" flow in Remote Access: an authenticated
8
+ * user mints a single-use code (short TTL), embeds it in a share link/QR, and
9
+ * the scanning device exchanges it for a normal auth session as the same user.
10
+ * The code is burned on claim (`claimed_at`) so a leaked link is useless once
11
+ * used or expired. Cleaned up alongside expired auth sessions.
12
+ */
13
+ export const up = (db: DatabaseConnection): void => {
14
+ debug.log('migration', 'Creating device_codes table...');
15
+
16
+ db.exec(`
17
+ CREATE TABLE IF NOT EXISTS device_codes (
18
+ id TEXT PRIMARY KEY,
19
+ code_hash TEXT NOT NULL UNIQUE,
20
+ user_id TEXT NOT NULL,
21
+ label TEXT,
22
+ expires_at TEXT NOT NULL,
23
+ claimed_at TEXT,
24
+ created_at TEXT NOT NULL,
25
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
26
+ )
27
+ `);
28
+
29
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_device_codes_user ON device_codes(user_id)`);
30
+
31
+ debug.log('migration', 'device_codes table created');
32
+ };
33
+
34
+ export const down = (db: DatabaseConnection): void => {
35
+ debug.log('migration', 'Dropping device_codes table...');
36
+ db.exec('DROP TABLE IF EXISTS device_codes');
37
+ debug.log('migration', 'device_codes table dropped');
38
+ };
@@ -0,0 +1,42 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Add user_agent + ip_address to auth_sessions for device identification';
5
+
6
+ /**
7
+ * Records which device/browser and IP each session was created from, so the
8
+ * "Your Devices" / Remote Access views can show a real picture ("Chrome on
9
+ * macOS · 1.2.3.4") instead of an opaque session id. Nullable — pre-existing
10
+ * sessions and no-auth sessions simply have no metadata.
11
+ */
12
+ export const up = (db: DatabaseConnection): void => {
13
+ debug.log('migration', 'Adding device metadata columns to auth_sessions...');
14
+ db.exec(`ALTER TABLE auth_sessions ADD COLUMN user_agent TEXT`);
15
+ db.exec(`ALTER TABLE auth_sessions ADD COLUMN ip_address TEXT`);
16
+ debug.log('migration', 'auth_sessions device metadata columns added');
17
+ };
18
+
19
+ export const down = (db: DatabaseConnection): void => {
20
+ debug.log('migration', 'Removing device metadata columns from auth_sessions...');
21
+ // SQLite pre-3.35 can't DROP COLUMN; recreate without the columns.
22
+ db.exec(`
23
+ CREATE TABLE auth_sessions_new (
24
+ id TEXT PRIMARY KEY,
25
+ user_id TEXT NOT NULL,
26
+ token_hash TEXT NOT NULL UNIQUE,
27
+ expires_at TEXT NOT NULL,
28
+ created_at TEXT NOT NULL,
29
+ last_active_at TEXT NOT NULL,
30
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
31
+ )
32
+ `);
33
+ db.exec(`
34
+ INSERT INTO auth_sessions_new (id, user_id, token_hash, expires_at, created_at, last_active_at)
35
+ SELECT id, user_id, token_hash, expires_at, created_at, last_active_at FROM auth_sessions
36
+ `);
37
+ db.exec(`DROP TABLE auth_sessions`);
38
+ db.exec(`ALTER TABLE auth_sessions_new RENAME TO auth_sessions`);
39
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_auth_sessions_token_hash ON auth_sessions(token_hash)`);
40
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_auth_sessions_user_id ON auth_sessions(user_id)`);
41
+ debug.log('migration', 'auth_sessions device metadata columns removed');
42
+ };
@@ -0,0 +1,43 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Add source column to auth_sessions to record how each session was created';
5
+
6
+ /**
7
+ * Records the provenance of every session ('setup' | 'invite' | 'device-link' |
8
+ * 'login' | 'pat' | 'no-auth') so the admin "Connected devices" view can show
9
+ * where each signed-in device came from. Nullable — pre-existing sessions simply
10
+ * have no recorded source.
11
+ */
12
+ export const up = (db: DatabaseConnection): void => {
13
+ debug.log('migration', 'Adding source column to auth_sessions...');
14
+ db.exec(`ALTER TABLE auth_sessions ADD COLUMN source TEXT`);
15
+ debug.log('migration', 'auth_sessions source column added');
16
+ };
17
+
18
+ export const down = (db: DatabaseConnection): void => {
19
+ debug.log('migration', 'Removing source column from auth_sessions...');
20
+ // SQLite pre-3.35 can't DROP COLUMN; recreate without it (keeping 061's columns).
21
+ db.exec(`
22
+ CREATE TABLE auth_sessions_new (
23
+ id TEXT PRIMARY KEY,
24
+ user_id TEXT NOT NULL,
25
+ token_hash TEXT NOT NULL UNIQUE,
26
+ expires_at TEXT NOT NULL,
27
+ created_at TEXT NOT NULL,
28
+ last_active_at TEXT NOT NULL,
29
+ user_agent TEXT,
30
+ ip_address TEXT,
31
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
32
+ )
33
+ `);
34
+ db.exec(`
35
+ INSERT INTO auth_sessions_new (id, user_id, token_hash, expires_at, created_at, last_active_at, user_agent, ip_address)
36
+ SELECT id, user_id, token_hash, expires_at, created_at, last_active_at, user_agent, ip_address FROM auth_sessions
37
+ `);
38
+ db.exec(`DROP TABLE auth_sessions`);
39
+ db.exec(`ALTER TABLE auth_sessions_new RENAME TO auth_sessions`);
40
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_auth_sessions_token_hash ON auth_sessions(token_hash)`);
41
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_auth_sessions_user_id ON auth_sessions(user_id)`);
42
+ debug.log('migration', 'auth_sessions source column removed');
43
+ };