@myrialabs/clopen 0.3.8 → 0.3.9
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/backend/auth/permissions.ts +41 -2
- package/backend/chat/stream-manager.ts +71 -0
- 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/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 +573 -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 +5 -115
- 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 +380 -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/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/ws/README.md +128 -3
- package/backend/ws/access.ts +56 -0
- package/backend/ws/chat/stream.ts +36 -12
- 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 +83 -31
- 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/read.ts +3 -1
- package/backend/ws/files/state.ts +3 -0
- package/backend/ws/files/watch.ts +7 -1
- 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 +5 -40
- 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 +4 -10
- package/backend/ws/projects/status.ts +2 -0
- package/backend/ws/sessions/crud.ts +22 -33
- 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 +12 -6
- package/backend/ws/terminal/session.ts +35 -14
- package/backend/ws/terminal/stream.ts +4 -1
- package/dist/assets/{index-DqAGCTFT.js → index-D8V2wj9B.js} +2 -2
- package/dist/assets/{main-DsED0rLr.js → main-C9nYVmnw.js} +206 -198
- package/dist/assets/main-hspyFOoK.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +4 -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-eWY9R8g9.css +0 -1
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
|
|
13
13
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
14
14
|
import type { z } from "zod";
|
|
15
|
+
import { projectContextService } from '../project-context';
|
|
15
16
|
|
|
16
17
|
/**
|
|
17
18
|
* Infer argument types from Zod schema
|
|
@@ -191,6 +192,18 @@ export function createRemoteMcpServer(
|
|
|
191
192
|
description: def.description,
|
|
192
193
|
inputSchema: def.schema,
|
|
193
194
|
}, async (args: Record<string, unknown>) => {
|
|
195
|
+
// Fast-fail when the owning chat stream has already been
|
|
196
|
+
// cancelled — the handler never runs. Without this, the
|
|
197
|
+
// engine subprocess dies on cancel but in-flight HTTP-MCP
|
|
198
|
+
// tool calls continue to drive puppeteer ops, surfacing as
|
|
199
|
+
// "preview keeps moving by itself" after interrupt.
|
|
200
|
+
const signal = projectContextService.getCurrentSignal();
|
|
201
|
+
if (signal?.aborted) {
|
|
202
|
+
return {
|
|
203
|
+
content: [{ type: 'text' as const, text: `Tool ${String(toolName)} was cancelled because the chat stream was interrupted.` }],
|
|
204
|
+
isError: true,
|
|
205
|
+
} as any;
|
|
206
|
+
}
|
|
194
207
|
return await def.handler(args) as any;
|
|
195
208
|
});
|
|
196
209
|
}
|
|
@@ -6,12 +6,20 @@ import { SERVER_ENV } from '../utils/env';
|
|
|
6
6
|
* Catches all errors and returns consistent error responses
|
|
7
7
|
*/
|
|
8
8
|
export function errorHandlerMiddleware(app: Elysia) {
|
|
9
|
-
return app.onError(({ code, error, set }) => {
|
|
10
|
-
|
|
9
|
+
return app.onError(({ code, error, set, request }) => {
|
|
10
|
+
// Build a single-line request descriptor so 404s/etc. can be traced
|
|
11
|
+
// back to the offending URL without dumping the full Error stack
|
|
12
|
+
// (which previously logged just "NOT_FOUND" with no path info).
|
|
13
|
+
let reqInfo = '';
|
|
14
|
+
try {
|
|
15
|
+
const url = new URL(request.url);
|
|
16
|
+
reqInfo = `${request.method} ${url.pathname}${url.search}`;
|
|
17
|
+
} catch { /* request.url unavailable */ }
|
|
11
18
|
|
|
12
19
|
// Handle different error types
|
|
13
20
|
switch (code) {
|
|
14
21
|
case 'VALIDATION':
|
|
22
|
+
console.error('[Error]', code, reqInfo, error.message);
|
|
15
23
|
set.status = 400;
|
|
16
24
|
return {
|
|
17
25
|
success: false,
|
|
@@ -20,6 +28,10 @@ export function errorHandlerMiddleware(app: Elysia) {
|
|
|
20
28
|
};
|
|
21
29
|
|
|
22
30
|
case 'NOT_FOUND':
|
|
31
|
+
// 404s are common in dev (probes, hot-reload pings, deep-link
|
|
32
|
+
// refreshes). Log the path at warn level instead of dumping
|
|
33
|
+
// the full Error stack on every miss.
|
|
34
|
+
console.warn('[404]', reqInfo || '(unknown path)');
|
|
23
35
|
set.status = 404;
|
|
24
36
|
return {
|
|
25
37
|
success: false,
|
|
@@ -28,6 +40,7 @@ export function errorHandlerMiddleware(app: Elysia) {
|
|
|
28
40
|
};
|
|
29
41
|
|
|
30
42
|
case 'PARSE':
|
|
43
|
+
console.error('[Error]', code, reqInfo);
|
|
31
44
|
set.status = 400;
|
|
32
45
|
return {
|
|
33
46
|
success: false,
|
|
@@ -36,6 +49,7 @@ export function errorHandlerMiddleware(app: Elysia) {
|
|
|
36
49
|
};
|
|
37
50
|
|
|
38
51
|
default:
|
|
52
|
+
console.error('[Error]', code, reqInfo, error);
|
|
39
53
|
set.status = 500;
|
|
40
54
|
return {
|
|
41
55
|
success: false,
|
|
@@ -479,7 +479,7 @@ export class BrowserPreviewService extends EventEmitter {
|
|
|
479
479
|
// ============================================================================
|
|
480
480
|
// Interaction & Autonomous Actions Methods
|
|
481
481
|
// ============================================================================
|
|
482
|
-
async performAutonomousActions(tabId: string, actions: BrowserAutonomousAction[]) {
|
|
482
|
+
async performAutonomousActions(tabId: string, actions: BrowserAutonomousAction[], abortSignal?: AbortSignal) {
|
|
483
483
|
const tab = this.getTab(tabId);
|
|
484
484
|
if (!tab) throw new Error('Tab not found or invalid');
|
|
485
485
|
|
|
@@ -487,7 +487,7 @@ export class BrowserPreviewService extends EventEmitter {
|
|
|
487
487
|
tabId,
|
|
488
488
|
tab,
|
|
489
489
|
actions,
|
|
490
|
-
() => this.isValidTab(tabId)
|
|
490
|
+
() => this.isValidTab(tabId) && !(abortSignal?.aborted ?? false)
|
|
491
491
|
);
|
|
492
492
|
|
|
493
493
|
return results;
|
|
@@ -497,12 +497,12 @@ export class BrowserPreviewService extends EventEmitter {
|
|
|
497
497
|
* Perform autonomous actions using tab object directly
|
|
498
498
|
* More efficient when tab is already available
|
|
499
499
|
*/
|
|
500
|
-
async performAutonomousActionsWithTab(tab: BrowserTab, actions: BrowserAutonomousAction[]) {
|
|
500
|
+
async performAutonomousActionsWithTab(tab: BrowserTab, actions: BrowserAutonomousAction[], abortSignal?: AbortSignal) {
|
|
501
501
|
const results = await this.interactionHandler.performAutonomousActions(
|
|
502
502
|
tab.id,
|
|
503
503
|
tab,
|
|
504
504
|
actions,
|
|
505
|
-
() => this.isValidTab(tab.id)
|
|
505
|
+
() => this.isValidTab(tab.id) && !(abortSignal?.aborted ?? false)
|
|
506
506
|
);
|
|
507
507
|
|
|
508
508
|
return results;
|
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('Project not found');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const project = projectQueries.getById(projectId);
|
|
14
|
+
if (!project) {
|
|
15
|
+
throw new Error('Project not found');
|
|
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('Session not found');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const userId = ws.getUserId(conn);
|
|
39
|
+
const hasAccess = projectQueries.userHasProject(userId, session.project_id);
|
|
40
|
+
if (!hasAccess) {
|
|
41
|
+
throw new Error('Session not found');
|
|
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('Message not found');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Message access inherits session access controls.
|
|
54
|
+
requireSessionAccess(conn, message.session_id);
|
|
55
|
+
return message;
|
|
56
|
+
}
|
|
@@ -14,6 +14,7 @@ import { debug } from '$shared/utils/logger';
|
|
|
14
14
|
import { ws } from '$backend/utils/ws';
|
|
15
15
|
import { broadcastPresence } from '../projects/status';
|
|
16
16
|
import { sessionQueries, messageQueries } from '../../database/queries';
|
|
17
|
+
import { requireSessionAccess } from '../access';
|
|
17
18
|
|
|
18
19
|
// ============================================================================
|
|
19
20
|
// Global stream lifecycle handler (module-level, not per-connection)
|
|
@@ -77,6 +78,7 @@ export const streamHandler = createRouter()
|
|
|
77
78
|
chatSessionId: t.String()
|
|
78
79
|
})
|
|
79
80
|
}, ({ data, conn }) => {
|
|
81
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
80
82
|
// Leave all previous chat sessions first (1 session at a time per connection)
|
|
81
83
|
ws.leaveAllChatSessions(conn);
|
|
82
84
|
ws.joinChatSession(conn, data.chatSessionId);
|
|
@@ -103,7 +105,7 @@ export const streamHandler = createRouter()
|
|
|
103
105
|
projectPath: t.String(),
|
|
104
106
|
prompt: t.Any(), // UserMessage object
|
|
105
107
|
engine: t.Object({
|
|
106
|
-
type: t.Union([t.Literal('claude-code'), t.Literal('opencode')]),
|
|
108
|
+
type: t.Union([t.Literal('claude-code'), t.Literal('opencode'), t.Literal('copilot'), t.Literal('codex'), t.Literal('qwen')]),
|
|
107
109
|
provider: t.String(),
|
|
108
110
|
model: t.Object({
|
|
109
111
|
id: t.String(),
|
|
@@ -120,6 +122,7 @@ export const streamHandler = createRouter()
|
|
|
120
122
|
})
|
|
121
123
|
})
|
|
122
124
|
}, async ({ data, conn }) => {
|
|
125
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
123
126
|
const projectId = ws.getProjectId(conn);
|
|
124
127
|
|
|
125
128
|
try {
|
|
@@ -291,6 +294,7 @@ export const streamHandler = createRouter()
|
|
|
291
294
|
chatSessionId: t.String()
|
|
292
295
|
})
|
|
293
296
|
}, async ({ data, conn }) => {
|
|
297
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
294
298
|
const projectId = ws.getProjectId(conn);
|
|
295
299
|
|
|
296
300
|
try {
|
|
@@ -422,7 +426,12 @@ export const streamHandler = createRouter()
|
|
|
422
426
|
}
|
|
423
427
|
})
|
|
424
428
|
|
|
425
|
-
// Handle AskUserQuestion answer from user
|
|
429
|
+
// Handle AskUserQuestion answer from user.
|
|
430
|
+
//
|
|
431
|
+
// Routed to the engine's built-in resolveUserAnswer (Claude: canUseTool,
|
|
432
|
+
// OpenCode: event hook). Codex has no callback hook in the SDK — when
|
|
433
|
+
// the SDK adds native support, route it here too instead of resurrecting
|
|
434
|
+
// the previous MCP-based fallback.
|
|
426
435
|
.on('chat:ask-user-answer', {
|
|
427
436
|
data: t.Object({
|
|
428
437
|
chatSessionId: t.String(),
|
|
@@ -430,6 +439,7 @@ export const streamHandler = createRouter()
|
|
|
430
439
|
answers: t.Record(t.String(), t.String())
|
|
431
440
|
})
|
|
432
441
|
}, async ({ data, conn }) => {
|
|
442
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
433
443
|
const projectId = ws.getProjectId(conn);
|
|
434
444
|
|
|
435
445
|
try {
|
|
@@ -439,15 +449,14 @@ export const streamHandler = createRouter()
|
|
|
439
449
|
answers: data.answers
|
|
440
450
|
});
|
|
441
451
|
|
|
442
|
-
const
|
|
452
|
+
const handled = streamManager.resolveUserAnswer(
|
|
443
453
|
data.chatSessionId,
|
|
444
454
|
projectId,
|
|
445
455
|
data.toolUseId,
|
|
446
456
|
data.answers
|
|
447
457
|
);
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
debug.warn('chat', 'Failed to resolve user answer for stream');
|
|
458
|
+
if (!handled) {
|
|
459
|
+
debug.warn('chat', 'Failed to resolve user answer (no engine handler for this toolUseId)');
|
|
451
460
|
}
|
|
452
461
|
} catch (error) {
|
|
453
462
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
|
@@ -479,6 +488,10 @@ export const streamHandler = createRouter()
|
|
|
479
488
|
}, async ({ data, conn }) => {
|
|
480
489
|
const projectId = ws.getProjectId(conn);
|
|
481
490
|
|
|
491
|
+
if (data.chatSessionId) {
|
|
492
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
493
|
+
}
|
|
494
|
+
|
|
482
495
|
const streamState = data.chatSessionId
|
|
483
496
|
? streamManager.getSessionStream(data.chatSessionId, projectId)
|
|
484
497
|
: undefined;
|
|
@@ -519,6 +532,7 @@ export const streamHandler = createRouter()
|
|
|
519
532
|
chatSessionId: t.String()
|
|
520
533
|
})
|
|
521
534
|
}, async ({ data, conn }) => {
|
|
535
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
522
536
|
const projectId = ws.getProjectId(conn);
|
|
523
537
|
const chatSessionId = data.chatSessionId;
|
|
524
538
|
|
|
@@ -564,7 +578,8 @@ export const streamHandler = createRouter()
|
|
|
564
578
|
messageId: t.Union([t.String(), t.Null()]),
|
|
565
579
|
messageTimestamp: t.Union([t.String(), t.Null()])
|
|
566
580
|
})
|
|
567
|
-
}, ({ data }) => {
|
|
581
|
+
}, ({ data, conn }) => {
|
|
582
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
568
583
|
const chatSessionId = data.chatSessionId;
|
|
569
584
|
|
|
570
585
|
// Store on server for late joiners / refresh (keyed by chatSessionId)
|
|
@@ -596,8 +611,11 @@ export const streamHandler = createRouter()
|
|
|
596
611
|
messageId: t.Union([t.String(), t.Null()]),
|
|
597
612
|
messageTimestamp: t.Union([t.String(), t.Null()])
|
|
598
613
|
})
|
|
599
|
-
}, ({ data }) => {
|
|
614
|
+
}, ({ data, conn }) => {
|
|
600
615
|
const chatSessionId = data.chatSessionId || '';
|
|
616
|
+
if (chatSessionId) {
|
|
617
|
+
requireSessionAccess(conn, chatSessionId);
|
|
618
|
+
}
|
|
601
619
|
const editState = chatSessionEditMode.get(chatSessionId);
|
|
602
620
|
return editState || { isEditing: false, messageId: null, messageTimestamp: null };
|
|
603
621
|
})
|
|
@@ -616,7 +634,8 @@ export const streamHandler = createRouter()
|
|
|
616
634
|
base64: t.String()
|
|
617
635
|
})))
|
|
618
636
|
})
|
|
619
|
-
}, ({ data }) => {
|
|
637
|
+
}, ({ data, conn }) => {
|
|
638
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
620
639
|
const chatSessionId = data.chatSessionId;
|
|
621
640
|
|
|
622
641
|
// Store latest input state on server for late-joining users (keyed by chatSessionId)
|
|
@@ -649,8 +668,11 @@ export const streamHandler = createRouter()
|
|
|
649
668
|
base64: t.String()
|
|
650
669
|
})))
|
|
651
670
|
})
|
|
652
|
-
}, ({ data }) => {
|
|
671
|
+
}, ({ data, conn }) => {
|
|
653
672
|
const chatSessionId = data.chatSessionId || '';
|
|
673
|
+
if (chatSessionId) {
|
|
674
|
+
requireSessionAccess(conn, chatSessionId);
|
|
675
|
+
}
|
|
654
676
|
const state = chatSessionInputState.get(chatSessionId);
|
|
655
677
|
return state || { text: '', senderId: '' };
|
|
656
678
|
})
|
|
@@ -665,7 +687,8 @@ export const streamHandler = createRouter()
|
|
|
665
687
|
modelId: t.String(),
|
|
666
688
|
modelName: t.String()
|
|
667
689
|
})
|
|
668
|
-
}, ({ data }) => {
|
|
690
|
+
}, ({ data, conn }) => {
|
|
691
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
669
692
|
const chatSessionId = data.chatSessionId;
|
|
670
693
|
|
|
671
694
|
// Store latest model state on server for late joiners / refresh
|
|
@@ -703,7 +726,8 @@ export const streamHandler = createRouter()
|
|
|
703
726
|
accountId: t.Union([t.Number(), t.Null()]),
|
|
704
727
|
accountName: t.Optional(t.Union([t.String(), t.Null()]))
|
|
705
728
|
})
|
|
706
|
-
}, ({ data }) => {
|
|
729
|
+
}, ({ data, conn }) => {
|
|
730
|
+
requireSessionAccess(conn, data.chatSessionId);
|
|
707
731
|
const chatSessionId = data.chatSessionId;
|
|
708
732
|
|
|
709
733
|
// Store latest account state on server for late joiners / refresh
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { WSConnection } from '$shared/utils/ws-server';
|
|
2
|
+
import { ws } from '$backend/utils/ws';
|
|
3
|
+
import { dbClientConnectionQueries } from '../../database/queries';
|
|
4
|
+
|
|
5
|
+
export interface DbClientPrincipal {
|
|
6
|
+
userId: string;
|
|
7
|
+
isAdmin: boolean;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function getDbClientPrincipal(conn: WSConnection): DbClientPrincipal {
|
|
11
|
+
const userId = ws.getUserId(conn);
|
|
12
|
+
const isAdmin = ws.getRole(conn) === 'admin';
|
|
13
|
+
return { userId, isAdmin };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function requireDbClientConnectionAccess(conn: WSConnection, connectionId: string) {
|
|
17
|
+
const { userId, isAdmin } = getDbClientPrincipal(conn);
|
|
18
|
+
return dbClientConnectionQueries.ensureAccess(connectionId, userId, isAdmin);
|
|
19
|
+
}
|
|
@@ -14,6 +14,7 @@ import type {
|
|
|
14
14
|
DbSslMode
|
|
15
15
|
} from '$shared/types/db-client';
|
|
16
16
|
import { debug } from '$shared/utils/logger';
|
|
17
|
+
import { getDbClientPrincipal, requireDbClientConnectionAccess } from './access';
|
|
17
18
|
|
|
18
19
|
const driverSchema = t.Union([
|
|
19
20
|
t.Literal('mysql'),
|
|
@@ -111,28 +112,34 @@ export const connectionsHandler = createRouter()
|
|
|
111
112
|
.http('db-client:list', {
|
|
112
113
|
data: t.Object({}),
|
|
113
114
|
response: t.Array(t.Any())
|
|
114
|
-
}, async () => {
|
|
115
|
+
}, async ({ conn }) => {
|
|
115
116
|
await initializeDatabase();
|
|
116
|
-
|
|
117
|
+
const { userId, isAdmin } = getDbClientPrincipal(conn);
|
|
118
|
+
return dbClientConnectionQueries.listForUser(userId, isAdmin);
|
|
117
119
|
})
|
|
118
120
|
|
|
119
121
|
.http('db-client:get', {
|
|
120
122
|
data: t.Object({ id: t.String({ minLength: 1 }) }),
|
|
121
123
|
response: t.Any()
|
|
122
|
-
}, async ({ data }) => {
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
|
|
124
|
+
}, async ({ data, conn }) => {
|
|
125
|
+
const { userId, isAdmin } = getDbClientPrincipal(conn);
|
|
126
|
+
const connection = dbClientConnectionQueries.getForUser(data.id, userId, isAdmin);
|
|
127
|
+
if (!connection) throw new Error('db-client connection not found');
|
|
128
|
+
return connection;
|
|
126
129
|
})
|
|
127
130
|
|
|
128
131
|
.http('db-client:create', {
|
|
129
132
|
data: connectionInputSchema,
|
|
130
133
|
response: t.Any()
|
|
131
|
-
}, async ({ data }) => {
|
|
134
|
+
}, async ({ data, conn }) => {
|
|
132
135
|
await initializeDatabase();
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
|
|
136
|
+
const { userId } = getDbClientPrincipal(conn);
|
|
137
|
+
const created = dbClientConnectionQueries.createForUser(
|
|
138
|
+
ensureInputDefaults(data as DbClientConnectionInput),
|
|
139
|
+
userId
|
|
140
|
+
);
|
|
141
|
+
debug.log('db-client', `created connection ${created.id} (${created.driver})`);
|
|
142
|
+
return created;
|
|
136
143
|
})
|
|
137
144
|
|
|
138
145
|
.http('db-client:update', {
|
|
@@ -141,7 +148,9 @@ export const connectionsHandler = createRouter()
|
|
|
141
148
|
patch: connectionPatchSchema
|
|
142
149
|
}),
|
|
143
150
|
response: t.Any()
|
|
144
|
-
}, async ({ data }) => {
|
|
151
|
+
}, async ({ data, conn }) => {
|
|
152
|
+
const { userId, isAdmin } = getDbClientPrincipal(conn);
|
|
153
|
+
requireDbClientConnectionAccess(conn, data.id);
|
|
145
154
|
const patch = data.patch as Partial<DbClientConnectionInput>;
|
|
146
155
|
const normalized: Partial<DbClientConnectionInput> = {
|
|
147
156
|
...patch,
|
|
@@ -149,32 +158,37 @@ export const connectionsHandler = createRouter()
|
|
|
149
158
|
};
|
|
150
159
|
// Drop the live adapter so the next access re-opens with new settings.
|
|
151
160
|
await connectionManager.release(data.id);
|
|
152
|
-
return dbClientConnectionQueries.
|
|
161
|
+
return dbClientConnectionQueries.updateForUser(data.id, normalized, userId, isAdmin);
|
|
153
162
|
})
|
|
154
163
|
|
|
155
164
|
.http('db-client:delete', {
|
|
156
165
|
data: t.Object({ id: t.String({ minLength: 1 }) }),
|
|
157
166
|
response: t.Object({ ok: t.Boolean() })
|
|
158
|
-
}, async ({ data }) => {
|
|
167
|
+
}, async ({ data, conn }) => {
|
|
168
|
+
const { userId, isAdmin } = getDbClientPrincipal(conn);
|
|
169
|
+
requireDbClientConnectionAccess(conn, data.id);
|
|
159
170
|
await connectionManager.release(data.id);
|
|
160
|
-
dbClientConnectionQueries.
|
|
171
|
+
dbClientConnectionQueries.deleteForUser(data.id, userId, isAdmin);
|
|
161
172
|
return { ok: true };
|
|
162
173
|
})
|
|
163
174
|
|
|
164
175
|
.http('db-client:test', {
|
|
165
176
|
data: connectionTestSchema,
|
|
166
177
|
response: healthSchema
|
|
167
|
-
}, async ({ data }) => {
|
|
178
|
+
}, async ({ data, conn }) => {
|
|
168
179
|
await initializeDatabase();
|
|
169
180
|
if (isInput(data)) {
|
|
170
181
|
return connectionManager.test(ensureInputDefaults(data as DbClientConnectionInput));
|
|
171
182
|
}
|
|
172
|
-
|
|
183
|
+
const id = (data as { id: string }).id;
|
|
184
|
+
requireDbClientConnectionAccess(conn, id);
|
|
185
|
+
return connectionManager.test({ id });
|
|
173
186
|
})
|
|
174
187
|
|
|
175
188
|
.http('db-client:health', {
|
|
176
189
|
data: t.Object({ id: t.String({ minLength: 1 }) }),
|
|
177
190
|
response: healthSchema
|
|
178
|
-
}, async ({ data }) => {
|
|
191
|
+
}, async ({ data, conn }) => {
|
|
192
|
+
requireDbClientConnectionAccess(conn, data.id);
|
|
179
193
|
return connectionManager.test({ id: data.id });
|
|
180
194
|
});
|
|
@@ -12,8 +12,8 @@
|
|
|
12
12
|
import { t } from 'elysia';
|
|
13
13
|
import { createRouter } from '$shared/utils/ws-server';
|
|
14
14
|
import { connectionManager } from '../../db-client/connection-manager';
|
|
15
|
-
import { dbClientConnectionQueries } from '../../database/queries';
|
|
16
15
|
import type { DbClientObjectDetails, DbClientQueryResult } from '$shared/types/db-client';
|
|
16
|
+
import { requireDbClientConnectionAccess } from './access';
|
|
17
17
|
|
|
18
18
|
type SqlDriver = 'mysql' | 'postgres' | 'sqlite';
|
|
19
19
|
|
|
@@ -154,10 +154,9 @@ export const ioHandler = createRouter()
|
|
|
154
154
|
content: t.String(),
|
|
155
155
|
mimeType: t.String()
|
|
156
156
|
})
|
|
157
|
-
}, async ({ data }) => {
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
const driver = conn.driver;
|
|
157
|
+
}, async ({ data, conn }) => {
|
|
158
|
+
const connection = requireDbClientConnectionAccess(conn, data.connectionId);
|
|
159
|
+
const driver = connection.driver;
|
|
161
160
|
const withData = data.schemaOnly ? false : (data.withData ?? true);
|
|
162
161
|
|
|
163
162
|
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
|
|
@@ -340,10 +339,9 @@ export const ioHandler = createRouter()
|
|
|
340
339
|
count: t.Number(),
|
|
341
340
|
message: t.String()
|
|
342
341
|
})
|
|
343
|
-
}, async ({ data }) => {
|
|
344
|
-
const
|
|
345
|
-
|
|
346
|
-
const driver = conn.driver;
|
|
342
|
+
}, async ({ data, conn }) => {
|
|
343
|
+
const connection = requireDbClientConnectionAccess(conn, data.connectionId);
|
|
344
|
+
const driver = connection.driver;
|
|
347
345
|
const adapter = await connectionManager.get(data.connectionId);
|
|
348
346
|
|
|
349
347
|
if (driver === 'mysql' || driver === 'postgres' || driver === 'sqlite') {
|