@myrialabs/clopen 0.3.8 → 0.3.10
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.
- package/README.md +22 -19
- package/backend/auth/auth-service.ts +56 -1
- package/backend/auth/permissions.ts +66 -2
- package/backend/auth/session-cleanup.ts +58 -0
- package/backend/chat/stream-manager.ts +143 -13
- package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
- package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
- package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
- package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
- package/backend/database/migrations/index.ts +29 -1
- package/backend/database/queries/db-client-connection-queries.ts +160 -54
- package/backend/database/queries/engine-queries.ts +12 -0
- package/backend/database/queries/project-queries.ts +10 -5
- package/backend/db-client/connection-manager.ts +9 -3
- package/backend/engine/README.md +1702 -0
- package/backend/engine/adapters/claude/models.ts +141 -0
- package/backend/engine/adapters/claude/stream.ts +1 -1
- package/backend/engine/adapters/codex/credential.ts +179 -0
- package/backend/engine/adapters/codex/error-handler.ts +65 -0
- package/backend/engine/adapters/codex/index.ts +1 -0
- package/backend/engine/adapters/codex/message-converter.ts +646 -0
- package/backend/engine/adapters/codex/models.ts +105 -0
- package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
- package/backend/engine/adapters/codex/session-fork.ts +149 -0
- package/backend/engine/adapters/codex/stream.ts +310 -0
- package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
- package/backend/engine/adapters/copilot/error-handler.ts +94 -0
- package/backend/engine/adapters/copilot/index.ts +1 -0
- package/backend/engine/adapters/copilot/message-converter.ts +973 -0
- package/backend/engine/adapters/copilot/models.ts +92 -0
- package/backend/engine/adapters/copilot/session-fork.ts +111 -0
- package/backend/engine/adapters/copilot/stream.ts +570 -0
- package/backend/engine/adapters/opencode/config.ts +56 -104
- package/backend/engine/adapters/opencode/error-handler.ts +71 -0
- package/backend/engine/adapters/opencode/models.ts +79 -0
- package/backend/engine/adapters/opencode/presets.ts +91 -0
- package/backend/engine/adapters/opencode/stream.ts +8 -114
- package/backend/engine/adapters/qwen/credential.ts +78 -0
- package/backend/engine/adapters/qwen/environment.ts +84 -0
- package/backend/engine/adapters/qwen/error-handler.ts +71 -0
- package/backend/engine/adapters/qwen/index.ts +1 -0
- package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
- package/backend/engine/adapters/qwen/models.ts +81 -0
- package/backend/engine/adapters/qwen/presets.ts +51 -0
- package/backend/engine/adapters/qwen/session-fork.ts +97 -0
- package/backend/engine/adapters/qwen/stream.ts +379 -0
- package/backend/engine/index.ts +35 -0
- package/backend/engine/install-recipes.ts +80 -1
- package/backend/engine/install-runner.ts +4 -0
- package/backend/files/path-browsing.ts +20 -0
- package/backend/git/git-service.ts +81 -11
- package/backend/git/git-spawn-validation.test.ts +75 -0
- package/backend/git/git-spawn-validation.ts +77 -0
- package/backend/index.ts +5 -0
- package/backend/mcp/README.md +84 -14
- package/backend/mcp/config.ts +218 -17
- package/backend/mcp/index.ts +2 -0
- package/backend/mcp/project-context.ts +55 -0
- package/backend/mcp/servers/browser-automation/actions.ts +6 -1
- package/backend/mcp/servers/helper.ts +13 -0
- package/backend/middleware/error-handler.ts +16 -2
- package/backend/preview/browser/browser-preview-service.ts +4 -4
- package/backend/preview/browser/browser-tab-manager.ts +23 -3
- package/backend/snapshot/gitignore.ts +4 -9
- package/backend/tunnel/cloudflared/binary.ts +2 -2
- package/backend/tunnel/global-tunnel-manager.ts +9 -3
- package/backend/utils/ws.ts +5 -1
- package/backend/ws/README.md +128 -3
- package/backend/ws/access.ts +56 -0
- package/backend/ws/auth/index.ts +14 -0
- package/backend/ws/auth/login.ts +3 -0
- package/backend/ws/auth/users.ts +61 -1
- package/backend/ws/chat/stream.ts +139 -22
- package/backend/ws/db-client/access.ts +19 -0
- package/backend/ws/db-client/connections.ts +31 -17
- package/backend/ws/db-client/io.ts +7 -9
- package/backend/ws/db-client/query.ts +86 -32
- package/backend/ws/db-client/schema.ts +9 -4
- package/backend/ws/db-client/structure.ts +22 -10
- package/backend/ws/engine/access.ts +39 -0
- package/backend/ws/engine/claude/accounts.ts +15 -10
- package/backend/ws/engine/codex/accounts.ts +516 -0
- package/backend/ws/engine/codex/index.ts +14 -0
- package/backend/ws/engine/codex/status.ts +87 -0
- package/backend/ws/engine/copilot/accounts.ts +122 -0
- package/backend/ws/engine/copilot/index.ts +13 -0
- package/backend/ws/engine/copilot/status.ts +54 -0
- package/backend/ws/engine/index.ts +7 -1
- package/backend/ws/engine/opencode/providers.ts +1 -1
- package/backend/ws/engine/qwen/accounts.ts +137 -0
- package/backend/ws/engine/qwen/index.ts +15 -0
- package/backend/ws/engine/qwen/presets.ts +40 -0
- package/backend/ws/engine/qwen/status.ts +54 -0
- package/backend/ws/files/path-access.ts +101 -0
- package/backend/ws/files/read.ts +26 -11
- package/backend/ws/files/search.ts +10 -6
- package/backend/ws/files/state.ts +3 -0
- package/backend/ws/files/watch.ts +7 -1
- package/backend/ws/files/write.ts +109 -15
- package/backend/ws/git/branch.ts +13 -19
- package/backend/ws/git/commit-message.ts +3 -4
- package/backend/ws/git/commit.ts +5 -7
- package/backend/ws/git/conflict.ts +7 -10
- package/backend/ws/git/diff.ts +7 -10
- package/backend/ws/git/log.ts +3 -4
- package/backend/ws/git/remote.ts +30 -43
- package/backend/ws/git/staging.ts +13 -19
- package/backend/ws/git/status.ts +7 -11
- package/backend/ws/messages/crud.ts +7 -13
- package/backend/ws/preview/access.ts +45 -0
- package/backend/ws/preview/browser/cleanup.ts +3 -11
- package/backend/ws/preview/browser/console.ts +7 -42
- package/backend/ws/preview/browser/interact.ts +2 -6
- package/backend/ws/preview/browser/native-ui.ts +5 -18
- package/backend/ws/preview/browser/stats.ts +2 -12
- package/backend/ws/preview/browser/tab-info.ts +4 -20
- package/backend/ws/preview/browser/tab.ts +4 -27
- package/backend/ws/preview/browser/webcodecs.ts +6 -47
- package/backend/ws/projects/crud.ts +15 -16
- package/backend/ws/projects/status.ts +5 -1
- package/backend/ws/sessions/crud.ts +31 -36
- package/backend/ws/settings/crud.ts +13 -13
- package/backend/ws/snapshot/restore.ts +5 -2
- package/backend/ws/snapshot/timeline.ts +3 -1
- package/backend/ws/system-tools/access.ts +28 -0
- package/backend/ws/system-tools/install.ts +13 -4
- package/backend/ws/system-tools/status.ts +5 -2
- package/backend/ws/terminal/access.ts +56 -0
- package/backend/ws/terminal/persistence.ts +13 -7
- package/backend/ws/terminal/session.ts +35 -14
- package/backend/ws/terminal/stream.ts +4 -1
- package/dist/assets/{index-DqAGCTFT.js → index-C1afGwHY.js} +2 -2
- package/dist/assets/main-CZb3Y_Z_.js +315 -0
- package/dist/assets/main-Cn8cX2DY.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +5 -1
- package/shared/constants/engines.ts +45 -140
- package/shared/types/database/schema.ts +1 -0
- package/shared/types/unified/common.ts +1 -1
- package/shared/types/unified/engine.ts +29 -1
- package/shared/types/unified/index.ts +2 -0
- package/shared/types/unified/message.ts +1 -1
- package/shared/types/unified/tool.ts +17 -2
- package/shared/utils/ws-server.ts +14 -0
- package/dist/assets/main-DsED0rLr.js +0 -304
- package/dist/assets/main-eWY9R8g9.css +0 -1
|
@@ -44,6 +44,7 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
44
44
|
// Tab activity tracking for cleanup
|
|
45
45
|
private tabActivity = new Map<string, number>();
|
|
46
46
|
private cleanupInterval: NodeJS.Timeout | null = null;
|
|
47
|
+
private signalHandlers: { sigterm: () => void; sigint: () => void } | null = null;
|
|
47
48
|
|
|
48
49
|
// Audio capture manager
|
|
49
50
|
private audioCapture = new BrowserAudioCapture();
|
|
@@ -1038,14 +1039,30 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
1038
1039
|
this.performCleanup();
|
|
1039
1040
|
}, CLEANUP_INTERVAL);
|
|
1040
1041
|
|
|
1041
|
-
// Cleanup on shutdown
|
|
1042
|
+
// Cleanup on shutdown — track references so we can remove them later
|
|
1043
|
+
// and prevent duplicate listeners if multiple BrowserTabManager
|
|
1044
|
+
// instances are created.
|
|
1042
1045
|
const cleanup = () => {
|
|
1043
1046
|
if (this.cleanupInterval) clearInterval(this.cleanupInterval);
|
|
1047
|
+
this.cleanupInterval = null;
|
|
1044
1048
|
this.tabActivity.clear();
|
|
1049
|
+
this.removeSignalHandlers();
|
|
1045
1050
|
};
|
|
1046
1051
|
|
|
1047
|
-
|
|
1048
|
-
process.on('
|
|
1052
|
+
this.signalHandlers = { sigterm: cleanup, sigint: cleanup };
|
|
1053
|
+
process.on('SIGTERM', this.signalHandlers.sigterm);
|
|
1054
|
+
process.on('SIGINT', this.signalHandlers.sigint);
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
/**
|
|
1058
|
+
* Remove previously registered signal handlers to prevent leaks
|
|
1059
|
+
* when multiple BrowserTabManager instances are created.
|
|
1060
|
+
*/
|
|
1061
|
+
private removeSignalHandlers(): void {
|
|
1062
|
+
if (!this.signalHandlers) return;
|
|
1063
|
+
process.off('SIGTERM', this.signalHandlers.sigterm);
|
|
1064
|
+
process.off('SIGINT', this.signalHandlers.sigint);
|
|
1065
|
+
this.signalHandlers = null;
|
|
1049
1066
|
}
|
|
1050
1067
|
|
|
1051
1068
|
/**
|
|
@@ -1148,6 +1165,9 @@ export class BrowserTabManager extends EventEmitter {
|
|
|
1148
1165
|
this.cleanupInterval = null;
|
|
1149
1166
|
}
|
|
1150
1167
|
|
|
1168
|
+
// Remove signal handlers to prevent leaks
|
|
1169
|
+
this.removeSignalHandlers();
|
|
1170
|
+
|
|
1151
1171
|
const tabIds = Array.from(this.tabs.keys());
|
|
1152
1172
|
|
|
1153
1173
|
if (tabIds.length > 0) {
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import fs from 'fs/promises';
|
|
12
12
|
import path from 'path';
|
|
13
13
|
import { debug } from '$shared/utils/logger';
|
|
14
|
+
import { execGit } from '../git/git-executor';
|
|
14
15
|
|
|
15
16
|
/**
|
|
16
17
|
* Safety-net directories to always exclude regardless of .gitignore.
|
|
@@ -49,15 +50,9 @@ async function scanWithGit(dirPath: string): Promise<string[] | null> {
|
|
|
49
50
|
}
|
|
50
51
|
|
|
51
52
|
try {
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
);
|
|
56
|
-
|
|
57
|
-
const output = await new Response(proc.stdout).text();
|
|
58
|
-
const exitCode = await proc.exited;
|
|
59
|
-
|
|
60
|
-
if (exitCode !== 0) return null;
|
|
53
|
+
const result = await execGit(['ls-files', '-co', '--exclude-standard'], dirPath, 60_000);
|
|
54
|
+
if (result.exitCode !== 0) return null;
|
|
55
|
+
const output = result.stdout;
|
|
61
56
|
|
|
62
57
|
const files: string[] = [];
|
|
63
58
|
for (const line of output.split('\n')) {
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
import { existsSync, mkdirSync, createWriteStream, chmodSync, unlinkSync, renameSync } from 'fs';
|
|
17
17
|
import { join, dirname } from 'path';
|
|
18
18
|
import { platform, arch } from 'os';
|
|
19
|
-
import {
|
|
19
|
+
import { execFileSync } from 'child_process';
|
|
20
20
|
import { getClopenDir } from '../../utils/paths';
|
|
21
21
|
import { resolveBinary } from '../../utils/cli';
|
|
22
22
|
import { debug } from '$shared/utils/logger';
|
|
@@ -148,7 +148,7 @@ export async function installBinary(version = 'latest'): Promise<string> {
|
|
|
148
148
|
// macOS: download .tgz, extract, rename
|
|
149
149
|
const tgzPath = `${binPath}.tgz`;
|
|
150
150
|
await download(url, tgzPath);
|
|
151
|
-
|
|
151
|
+
execFileSync('tar', ['-xzf', tgzPath], { cwd: dirname(binPath), stdio: 'pipe' });
|
|
152
152
|
unlinkSync(tgzPath);
|
|
153
153
|
// tar extracts as "cloudflared" in the same directory
|
|
154
154
|
const extractedPath = join(dirname(binPath), 'cloudflared');
|
|
@@ -195,7 +195,9 @@ class GlobalTunnelManager {
|
|
|
195
195
|
if (instance.autoStopTimer) clearTimeout(instance.autoStopTimer);
|
|
196
196
|
try {
|
|
197
197
|
instance.tunnel.stop();
|
|
198
|
-
} catch {
|
|
198
|
+
} catch (err) {
|
|
199
|
+
debug.warn('tunnel', `Failed to stop quick tunnel on port ${port}:`, err);
|
|
200
|
+
}
|
|
199
201
|
this.quickTunnels.delete(port);
|
|
200
202
|
debug.log('tunnel', `Quick tunnel stopped on port ${port}`);
|
|
201
203
|
this.notifyStatusChanged();
|
|
@@ -297,7 +299,9 @@ class GlobalTunnelManager {
|
|
|
297
299
|
|
|
298
300
|
try {
|
|
299
301
|
instance.tunnel.stop();
|
|
300
|
-
} catch {
|
|
302
|
+
} catch (err) {
|
|
303
|
+
debug.warn('tunnel', `Failed to stop remote tunnel ${instance.label}:`, err);
|
|
304
|
+
}
|
|
301
305
|
this.remoteTunnels.delete(configId);
|
|
302
306
|
debug.log('tunnel', `Remote tunnel stopped: ${instance.label}`);
|
|
303
307
|
this.notifyStatusChanged();
|
|
@@ -548,7 +552,9 @@ class GlobalTunnelManager {
|
|
|
548
552
|
|
|
549
553
|
try {
|
|
550
554
|
instance.tunnel.stop();
|
|
551
|
-
} catch {
|
|
555
|
+
} catch (err) {
|
|
556
|
+
debug.warn('tunnel', `Failed to stop local tunnel ${instance.name}:`, err);
|
|
557
|
+
}
|
|
552
558
|
this.localTunnels.delete(configId);
|
|
553
559
|
debug.log('tunnel', `Local tunnel stopped: ${instance.name}`);
|
|
554
560
|
this.notifyStatusChanged();
|
package/backend/utils/ws.ts
CHANGED
|
@@ -182,7 +182,11 @@ class WSServer {
|
|
|
182
182
|
// Run all registered cleanup functions
|
|
183
183
|
if (state?.cleanups.size) {
|
|
184
184
|
for (const cleanup of state.cleanups) {
|
|
185
|
-
try {
|
|
185
|
+
try {
|
|
186
|
+
cleanup();
|
|
187
|
+
} catch (err) {
|
|
188
|
+
debug.warn('websocket', `Cleanup error for connection ${id}:`, err);
|
|
189
|
+
}
|
|
186
190
|
}
|
|
187
191
|
debug.log('websocket', `Ran ${state.cleanups.size} cleanup(s) for connection ${id}`);
|
|
188
192
|
}
|
package/backend/ws/README.md
CHANGED
|
@@ -129,7 +129,7 @@ export const wsRouter = createRouter()
|
|
|
129
129
|
### 3. Use in Frontend
|
|
130
130
|
|
|
131
131
|
```typescript
|
|
132
|
-
import ws from '$
|
|
132
|
+
import ws from '$frontend/utils/ws';
|
|
133
133
|
|
|
134
134
|
// HTTP-style request-response
|
|
135
135
|
try {
|
|
@@ -781,10 +781,10 @@ ws.getConnectionCount(projectId?)
|
|
|
781
781
|
|
|
782
782
|
### Frontend Client API
|
|
783
783
|
|
|
784
|
-
**File: `frontend/
|
|
784
|
+
**File: `frontend/utils/ws.ts`**
|
|
785
785
|
|
|
786
786
|
```typescript
|
|
787
|
-
import ws from '$
|
|
787
|
+
import ws from '$frontend/utils/ws';
|
|
788
788
|
|
|
789
789
|
// HTTP request
|
|
790
790
|
const data = await ws.http('namespace:action', { ... });
|
|
@@ -1286,6 +1286,114 @@ email: t.String({ format: 'email' })
|
|
|
1286
1286
|
|
|
1287
1287
|
---
|
|
1288
1288
|
|
|
1289
|
+
### 10. Authorization Guards (IDOR Prevention)
|
|
1290
|
+
|
|
1291
|
+
Connection context (Best Practice 6) tells you **who** is calling. Authorization guards
|
|
1292
|
+
verify **whether they may touch the resource they named in the payload**. Required
|
|
1293
|
+
whenever a handler accepts a `projectId`, `sessionId`, `messageId`, `streamId`,
|
|
1294
|
+
`projectPath`, or any other resource id from the client.
|
|
1295
|
+
|
|
1296
|
+
Guards live in **two tiers**:
|
|
1297
|
+
|
|
1298
|
+
1. **Global guards** in `backend/ws/access.ts` — the cross-cutting checks every
|
|
1299
|
+
module reuses (project membership, chat-session ownership, message ownership).
|
|
1300
|
+
2. **Scoped guards** in `backend/ws/<module>/access.ts` — module-specific helpers
|
|
1301
|
+
that resolve module-owned resources to one of the global checks (or apply
|
|
1302
|
+
admin/ownership rules unique to that module). They exist so handlers don't
|
|
1303
|
+
re-implement the same `manager.get(id) → null check → requireProjectAccess`
|
|
1304
|
+
boilerplate, and so subtle module-specific rules (e.g. "this engine setup
|
|
1305
|
+
PTY belongs to a single admin") have one home.
|
|
1306
|
+
|
|
1307
|
+
**Global guards (`backend/ws/access.ts`):**
|
|
1308
|
+
|
|
1309
|
+
| Helper | Use when handler accepts… |
|
|
1310
|
+
| ------------------------------- | ------------------------------------------------------------------- |
|
|
1311
|
+
| `requireProjectAccess` | a `projectId` (or a path/PTY/stream you resolved to a `projectId`) |
|
|
1312
|
+
| `requireSessionAccess` | a `chatSessionId` / `sessionId` from `chat_sessions` |
|
|
1313
|
+
| `requireMessageAccess` | a `messageId` from `chat_messages` |
|
|
1314
|
+
| `requireCurrentProjectAccess` | the handler relies on `ws.getProjectId(conn)` and must enforce it |
|
|
1315
|
+
|
|
1316
|
+
**Scoped guards (`backend/ws/<module>/access.ts`):**
|
|
1317
|
+
|
|
1318
|
+
| Module | Helper | Use when handler accepts… |
|
|
1319
|
+
| ------------- | ----------------------------------- | ------------------------------------------------------------------------------- |
|
|
1320
|
+
| `terminal` | `requirePtySessionAccess` | a PTY `sessionId` — resolves to its owning project, then `requireProjectAccess` |
|
|
1321
|
+
| `terminal` | `requireTerminalStreamAccess` | a `streamId` — same pattern |
|
|
1322
|
+
| `terminal` | `requireTerminalLookupAccess` | a `(sessionId, streamId?)` pair (used by `terminal:missed-output`) |
|
|
1323
|
+
| `preview` | `requireBrowserPreviewAccess` | the connection's current project — adds membership check + service lookup |
|
|
1324
|
+
| `preview` | `requireBrowserTabAccess` | an optional `tabId` — combines membership check with active/explicit tab lookup |
|
|
1325
|
+
| `db-client` | `requireDbClientConnectionAccess` | a connection id from `db_client_connections` (admin override + owner check) |
|
|
1326
|
+
| `system-tools`| `requireInstallSessionAccess` | a system-tools install `sessionId` — owner check |
|
|
1327
|
+
| `engine` | `requireSetupSessionAccess` | a setup-flow `setupId` — admin who started the flow only |
|
|
1328
|
+
|
|
1329
|
+
**DO:**
|
|
1330
|
+
```typescript
|
|
1331
|
+
.http('snapshot:restore', {
|
|
1332
|
+
data: t.Object({ sessionId: t.String(), messageId: t.String() })
|
|
1333
|
+
}, async ({ data, conn }) => {
|
|
1334
|
+
requireSessionAccess(conn, data.sessionId); // ✅ global guard before any work
|
|
1335
|
+
// … perform restore
|
|
1336
|
+
})
|
|
1337
|
+
|
|
1338
|
+
.on('terminal:input', {
|
|
1339
|
+
data: t.Object({ sessionId: t.String(), data: t.Any() })
|
|
1340
|
+
}, async ({ data, conn }) => {
|
|
1341
|
+
const ptySession = requirePtySessionAccess(conn, data.sessionId); // ✅ scoped guard
|
|
1342
|
+
// … forward input
|
|
1343
|
+
})
|
|
1344
|
+
|
|
1345
|
+
.http('preview:browser-tab-stats', {
|
|
1346
|
+
data: t.Object({ tabId: t.Optional(t.String()) })
|
|
1347
|
+
}, async ({ data, conn }) => {
|
|
1348
|
+
const { previewService, tab } = requireBrowserTabAccess(conn, data.tabId); // ✅
|
|
1349
|
+
// … return stats
|
|
1350
|
+
})
|
|
1351
|
+
```
|
|
1352
|
+
|
|
1353
|
+
**DON'T:**
|
|
1354
|
+
```typescript
|
|
1355
|
+
.http('snapshot:restore', {
|
|
1356
|
+
data: t.Object({ sessionId: t.String() })
|
|
1357
|
+
}, async ({ data }) => {
|
|
1358
|
+
// ❌ Anyone with a session id can mutate another user's project
|
|
1359
|
+
await snapshotService.restore(data.sessionId);
|
|
1360
|
+
})
|
|
1361
|
+
|
|
1362
|
+
.http('preview:browser-tab-stats', {
|
|
1363
|
+
data: t.Object({ tabId: t.Optional(t.String()) })
|
|
1364
|
+
}, async ({ conn }) => {
|
|
1365
|
+
// ❌ Trusts the conn's projectId without verifying membership; a stray
|
|
1366
|
+
// connection in another project's room can drive that project's browser.
|
|
1367
|
+
const projectId = ws.getProjectId(conn);
|
|
1368
|
+
const previewService = browserPreviewServiceManager.getService(projectId);
|
|
1369
|
+
})
|
|
1370
|
+
```
|
|
1371
|
+
|
|
1372
|
+
**Why:**
|
|
1373
|
+
- Connection identity ≠ resource ownership. A user authenticated as Alice can still
|
|
1374
|
+
send Bob's `sessionId` in the payload — the guard is what stops that.
|
|
1375
|
+
- Guards throw on miss; treat them as fail-closed. Never `try/catch` away an access error.
|
|
1376
|
+
- DB-layer functions (`projectQueries.setFilesPanelState`, etc.) must NOT silently
|
|
1377
|
+
upsert membership rows (e.g., `INSERT OR IGNORE INTO user_projects`); that pattern
|
|
1378
|
+
bypasses the guard. Membership is established only through `projects:join` flows.
|
|
1379
|
+
|
|
1380
|
+
**When you need a new shape of guard:**
|
|
1381
|
+
- If the rule is general (cross-module), extend `backend/ws/access.ts`.
|
|
1382
|
+
- If the rule is module-specific (resolves a manager-owned resource, applies an
|
|
1383
|
+
admin-override unique to that module, etc.), put it in
|
|
1384
|
+
`backend/ws/<module>/access.ts` and import the global helpers it composes with.
|
|
1385
|
+
- Either way, keep the audit surface in `access.ts` files — never inline ad-hoc
|
|
1386
|
+
ownership queries in handlers.
|
|
1387
|
+
|
|
1388
|
+
**Router-level admin gating.** Some namespaces operate on global system state
|
|
1389
|
+
(engine credentials, system tools, settings). Those routes are gated to admins
|
|
1390
|
+
*before* the handler runs by adding them to `ADMIN_ONLY_ROUTES` in
|
|
1391
|
+
`backend/auth/permissions.ts`. The scoped `access.ts` then covers leftover
|
|
1392
|
+
per-resource ownership inside that admin set (e.g. one admin cannot drive
|
|
1393
|
+
another admin's setup PTY).
|
|
1394
|
+
|
|
1395
|
+
---
|
|
1396
|
+
|
|
1289
1397
|
## Troubleshooting
|
|
1290
1398
|
|
|
1291
1399
|
### Handler Not Working
|
|
@@ -1434,6 +1542,23 @@ Use this checklist when creating or auditing modules:
|
|
|
1434
1542
|
- [ ] User-specific events use `user` scope
|
|
1435
1543
|
- [ ] Project-shared events use `project` scope
|
|
1436
1544
|
|
|
1545
|
+
### 6. Authorization Guards
|
|
1546
|
+
- [ ] Every handler that accepts a resource id (`projectId`, `sessionId`, `messageId`,
|
|
1547
|
+
`streamId`, `projectPath`, `tabId`, etc.) calls the matching `require*Access`
|
|
1548
|
+
helper BEFORE touching the resource
|
|
1549
|
+
- [ ] Cross-cutting ids (project / chat-session / message) use the global helpers
|
|
1550
|
+
in `backend/ws/access.ts`
|
|
1551
|
+
- [ ] Module-owned resources (PTY sessions, browser tabs, install sessions, engine
|
|
1552
|
+
setup PTYs, db-client connections) use the scoped helpers in
|
|
1553
|
+
`backend/ws/<module>/access.ts` — handlers don't re-implement the
|
|
1554
|
+
`manager.get(id) → null check → requireProjectAccess` boilerplate
|
|
1555
|
+
- [ ] Handlers that rely on connection's current project use either
|
|
1556
|
+
`requireCurrentProjectAccess` (global) or a scoped wrapper that calls it
|
|
1557
|
+
(e.g. `requireBrowserPreviewAccess`)
|
|
1558
|
+
- [ ] Mutation routes for global system state (engine credentials, system tools,
|
|
1559
|
+
settings) appear in `ADMIN_ONLY_ROUTES` in `backend/auth/permissions.ts`
|
|
1560
|
+
- [ ] DB-layer functions do NOT silently `INSERT OR IGNORE` membership rows
|
|
1561
|
+
|
|
1437
1562
|
---
|
|
1438
1563
|
|
|
1439
1564
|
## Additional Resources
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { WSConnection } from '$shared/utils/ws-server';
|
|
2
|
+
import type { Project, ChatSession, DatabaseMessage } from '$shared/types/database/schema';
|
|
3
|
+
import { ws } from '$backend/utils/ws';
|
|
4
|
+
import { projectQueries, sessionQueries, messageQueries } from '$backend/database/queries';
|
|
5
|
+
|
|
6
|
+
export function requireProjectAccess(conn: WSConnection, projectId: string): Project {
|
|
7
|
+
const userId = ws.getUserId(conn);
|
|
8
|
+
const hasAccess = projectQueries.userHasProject(userId, projectId);
|
|
9
|
+
if (!hasAccess) {
|
|
10
|
+
throw new Error('Access denied');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const project = projectQueries.getById(projectId);
|
|
14
|
+
if (!project) {
|
|
15
|
+
throw new Error('Access denied');
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
return project;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function requireCurrentProjectAccess(conn: WSConnection): {
|
|
22
|
+
userId: string;
|
|
23
|
+
projectId: string;
|
|
24
|
+
project: Project;
|
|
25
|
+
} {
|
|
26
|
+
const userId = ws.getUserId(conn);
|
|
27
|
+
const projectId = ws.getProjectId(conn);
|
|
28
|
+
const project = requireProjectAccess(conn, projectId);
|
|
29
|
+
return { userId, projectId, project };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function requireSessionAccess(conn: WSConnection, sessionId: string): ChatSession {
|
|
33
|
+
const session = sessionQueries.getById(sessionId);
|
|
34
|
+
if (!session) {
|
|
35
|
+
throw new Error('Access denied');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const userId = ws.getUserId(conn);
|
|
39
|
+
const hasAccess = projectQueries.userHasProject(userId, session.project_id);
|
|
40
|
+
if (!hasAccess) {
|
|
41
|
+
throw new Error('Access denied');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return session;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function requireMessageAccess(conn: WSConnection, messageId: string): DatabaseMessage {
|
|
48
|
+
const message = messageQueries.getById(messageId);
|
|
49
|
+
if (!message) {
|
|
50
|
+
throw new Error('Access denied');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Message access inherits session access controls.
|
|
54
|
+
requireSessionAccess(conn, message.session_id);
|
|
55
|
+
return message;
|
|
56
|
+
}
|
package/backend/ws/auth/index.ts
CHANGED
|
@@ -18,4 +18,18 @@ export const authRouter = createRouter()
|
|
|
18
18
|
// Declare auth:force-logout event (emitted when auth mode switches to required)
|
|
19
19
|
.emit('auth:force-logout', t.Object({
|
|
20
20
|
reason: t.String()
|
|
21
|
+
}))
|
|
22
|
+
// Declare auth:user-projects-changed event (broadcast on every assignment
|
|
23
|
+
// change so the target user's navigator and any admin viewing the
|
|
24
|
+
// per-user projects modal can both refresh in realtime).
|
|
25
|
+
.emit('auth:user-projects-changed', t.Object({
|
|
26
|
+
type: t.Union([t.Literal('assigned'), t.Literal('unassigned')]),
|
|
27
|
+
userId: t.String(),
|
|
28
|
+
projectId: t.String()
|
|
29
|
+
}))
|
|
30
|
+
// Declare auth:users-changed event (broadcast when a user is created or
|
|
31
|
+
// removed, so any admin viewing the user list refreshes in realtime).
|
|
32
|
+
.emit('auth:users-changed', t.Object({
|
|
33
|
+
type: t.Union([t.Literal('added'), t.Literal('removed')]),
|
|
34
|
+
userId: t.String()
|
|
21
35
|
}));
|
package/backend/ws/auth/login.ts
CHANGED
|
@@ -190,6 +190,9 @@ export const loginHandler = createRouter()
|
|
|
190
190
|
const tokenHash = (await import('$backend/auth/tokens')).hashToken(result.sessionToken);
|
|
191
191
|
ws.setAuth(conn, result.user.id, result.user.role, tokenHash);
|
|
192
192
|
|
|
193
|
+
// Notify admin sessions so their User Management list refreshes.
|
|
194
|
+
ws.emit.global('auth:users-changed', { type: 'added', userId: result.user.id });
|
|
195
|
+
|
|
193
196
|
return result;
|
|
194
197
|
} catch (err) {
|
|
195
198
|
authRateLimiter.recordFailure(ip, 'auth:accept-invite');
|
package/backend/ws/auth/users.ts
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
import { t } from 'elysia';
|
|
2
2
|
import { createRouter } from '$shared/utils/ws-server';
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
listUsers,
|
|
5
|
+
removeUser,
|
|
6
|
+
listUserProjects,
|
|
7
|
+
assignProjectToUser,
|
|
8
|
+
unassignProjectFromUser
|
|
9
|
+
} from '$backend/auth/auth-service';
|
|
10
|
+
import { ws } from '$backend/utils/ws';
|
|
4
11
|
|
|
5
12
|
export const usersHandler = createRouter()
|
|
6
13
|
// List all users (admin only — enforced by auth gate)
|
|
@@ -28,5 +35,58 @@ export const usersHandler = createRouter()
|
|
|
28
35
|
})
|
|
29
36
|
}, async ({ data }) => {
|
|
30
37
|
removeUser(data.userId);
|
|
38
|
+
ws.emit.global('auth:users-changed', { type: 'removed', userId: data.userId });
|
|
31
39
|
return { success: true };
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
// List projects assigned to a specific user (admin only)
|
|
43
|
+
.http('auth:list-user-projects', {
|
|
44
|
+
data: t.Object({
|
|
45
|
+
userId: t.String({ minLength: 1 })
|
|
46
|
+
}),
|
|
47
|
+
response: t.Array(t.Any())
|
|
48
|
+
}, async ({ data }) => {
|
|
49
|
+
return listUserProjects(data.userId);
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
// Assign a project to a user (admin only)
|
|
53
|
+
.http('auth:assign-project', {
|
|
54
|
+
data: t.Object({
|
|
55
|
+
userId: t.String({ minLength: 1 }),
|
|
56
|
+
projectId: t.String({ minLength: 1 })
|
|
57
|
+
}),
|
|
58
|
+
response: t.Object({
|
|
59
|
+
added: t.Boolean()
|
|
60
|
+
})
|
|
61
|
+
}, async ({ data }) => {
|
|
62
|
+
const added = assignProjectToUser(data.userId, data.projectId);
|
|
63
|
+
if (added) {
|
|
64
|
+
ws.emit.global('auth:user-projects-changed', {
|
|
65
|
+
type: 'assigned',
|
|
66
|
+
userId: data.userId,
|
|
67
|
+
projectId: data.projectId
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return { added };
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
// Revoke a user's access to a project (admin only)
|
|
74
|
+
.http('auth:unassign-project', {
|
|
75
|
+
data: t.Object({
|
|
76
|
+
userId: t.String({ minLength: 1 }),
|
|
77
|
+
projectId: t.String({ minLength: 1 })
|
|
78
|
+
}),
|
|
79
|
+
response: t.Object({
|
|
80
|
+
removed: t.Boolean()
|
|
81
|
+
})
|
|
82
|
+
}, async ({ data }) => {
|
|
83
|
+
const removed = unassignProjectFromUser(data.userId, data.projectId);
|
|
84
|
+
if (removed) {
|
|
85
|
+
ws.emit.global('auth:user-projects-changed', {
|
|
86
|
+
type: 'unassigned',
|
|
87
|
+
userId: data.userId,
|
|
88
|
+
projectId: data.projectId
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
return { removed };
|
|
32
92
|
});
|