@myrialabs/clopen 0.4.34 → 0.4.36
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/artifacts/sync.test.ts +63 -0
- package/backend/artifacts/sync.ts +56 -3
- package/backend/auth/permissions.ts +7 -0
- package/backend/containers/actions.ts +316 -0
- package/backend/containers/disk-usage.test.ts +68 -0
- package/backend/containers/disk-usage.ts +170 -0
- package/backend/containers/logs.ts +335 -0
- package/backend/containers/monitor.ts +410 -0
- package/backend/containers/parse.test.ts +599 -0
- package/backend/containers/parse.ts +905 -0
- package/backend/containers/port-index.test.ts +91 -0
- package/backend/containers/port-index.ts +198 -0
- package/backend/containers/prune-job.test.ts +148 -0
- package/backend/containers/prune-job.ts +129 -0
- package/backend/containers/pty-backend.ts +337 -0
- package/backend/containers/pty.ts +114 -0
- package/backend/containers/runtime.ts +218 -0
- package/backend/containers/scan.ts +293 -0
- package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +1 -0
- package/backend/database/queries/session-queries.ts +50 -11
- package/backend/database/queries/worktree-queries.ts +148 -0
- package/backend/engine/adapters/opencode/server.ts +389 -83
- package/backend/engine/adapters/opencode/stream.ts +14 -14
- package/backend/engine/hot-reload.ts +25 -10
- package/backend/files/file-watcher.test.ts +105 -0
- package/backend/files/file-watcher.ts +80 -10
- package/backend/git/git-service.test.ts +33 -0
- package/backend/git/git-service.ts +7 -3
- package/backend/git/nested-repos.test.ts +292 -1
- package/backend/git/nested-repos.ts +330 -17
- package/backend/host/metrics.test.ts +110 -0
- package/backend/host/metrics.ts +235 -0
- package/backend/{ports → host}/runner.ts +19 -10
- package/backend/index.ts +16 -4
- package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
- package/backend/ports/attribute.test.ts +3 -2
- package/backend/ports/attribute.ts +6 -45
- package/backend/ports/kill.ts +1 -1
- package/backend/ports/monitor.ts +1 -1
- package/backend/ports/processes.ts +1 -1
- package/backend/ports/scan-host.ts +77 -8
- package/backend/ports/scan.test.ts +1 -1
- package/backend/ports/scan.ts +1 -1
- package/backend/ports/ssh-lineage.ts +1 -1
- package/backend/preview/browser/browser-pool.ts +81 -0
- package/backend/preview/browser/browser-preview-service.ts +142 -32
- package/backend/preview/browser/browser-tab-manager.ts +350 -113
- package/backend/preview/browser/browser-video-capture.ts +84 -31
- package/backend/preview/browser/types.ts +9 -0
- package/backend/projects/project-cleanup.integration.test.ts +1 -1
- package/backend/projects/project-cleanup.ts +7 -1
- package/backend/projects/shell-ownership.ts +65 -0
- package/backend/snapshot/snapshot-service.ts +6 -2
- package/backend/terminal/ptykit.ts +35 -6
- package/backend/utils/ws.ts +21 -1
- package/backend/worktrees/clone.ts +222 -0
- package/backend/worktrees/index.ts +29 -0
- package/backend/worktrees/merge.test.ts +93 -0
- package/backend/worktrees/merge.ts +232 -0
- package/backend/worktrees/paths.test.ts +60 -0
- package/backend/worktrees/paths.ts +60 -0
- package/backend/worktrees/resolve.ts +67 -0
- package/backend/worktrees/service.ts +315 -0
- package/backend/worktrees/tree.ts +59 -0
- package/backend/ws/access.ts +18 -0
- package/backend/ws/artifacts/generate.ts +2 -2
- package/backend/ws/chat/stream.ts +9 -2
- package/backend/ws/containers/actions.ts +156 -0
- package/backend/ws/containers/index.ts +43 -0
- package/backend/ws/containers/list.ts +146 -0
- package/backend/ws/containers/logs.ts +43 -0
- package/backend/ws/containers/tunnel.ts +101 -0
- package/backend/ws/files/panel-state-scope.test.ts +102 -0
- package/backend/ws/files/path-access.test.ts +93 -1
- package/backend/ws/files/path-access.ts +54 -5
- package/backend/ws/files/read.ts +15 -10
- package/backend/ws/files/search.ts +7 -7
- package/backend/ws/files/state.ts +70 -8
- package/backend/ws/files/watch.ts +16 -14
- package/backend/ws/git/branch-name.ts +3 -3
- package/backend/ws/git/branch.ts +15 -15
- package/backend/ws/git/commit-message.ts +3 -3
- package/backend/ws/git/commit.ts +17 -17
- package/backend/ws/git/conflict.ts +10 -10
- package/backend/ws/git/diff.ts +9 -9
- package/backend/ws/git/ignored.ts +9 -9
- package/backend/ws/git/log.ts +6 -4
- package/backend/ws/git/remote.ts +43 -43
- package/backend/ws/git/staging.ts +16 -16
- package/backend/ws/git/status.ts +47 -37
- package/backend/ws/index.ts +6 -0
- package/backend/ws/message-rate-limiter.test.ts +45 -0
- package/backend/ws/message-rate-limiter.ts +34 -3
- package/backend/ws/preview/access.ts +11 -3
- package/backend/ws/projects/index.ts +5 -1
- package/backend/ws/projects/info.test.ts +54 -0
- package/backend/ws/projects/info.ts +398 -0
- package/backend/ws/sessions/crud.ts +21 -6
- package/backend/ws/snapshot/restore.ts +11 -14
- package/backend/ws/ssh/connections.ts +8 -0
- package/backend/ws/system/device-info.ts +70 -96
- package/backend/ws/worktrees/crud.ts +187 -0
- package/backend/ws/worktrees/index.ts +33 -0
- package/backend/ws/worktrees/transfer.ts +88 -0
- package/dist/assets/{index-vW2RpdHu.js → index-Bg-SUCFg.js} +1 -1
- package/dist/assets/{index-gGTMFUa8.js → index-Cz4YpHVi.js} +1 -1
- package/dist/assets/main-9G7IpQpK.css +1 -0
- package/dist/assets/main-BofFsH8E.js +1085 -0
- package/dist/index.html +2 -2
- package/dist/manifest.json +9 -2
- package/package.json +1 -1
- package/shared/types/containers/container.ts +366 -0
- package/shared/types/containers/index.ts +5 -0
- package/shared/types/database/schema.ts +26 -0
- package/shared/types/host/index.ts +18 -0
- package/shared/types/ports/port.ts +47 -9
- package/shared/utils/logger.ts +3 -0
- package/shared/utils/workspace-scope.test.ts +80 -0
- package/shared/utils/workspace-scope.ts +57 -0
- package/shared/utils/ws-client.ts +92 -17
- package/shared/utils/ws-server.ts +83 -16
- package/dist/assets/main-CYCMEbXB.css +0 -1
- package/dist/assets/main-ZCojSzvW.js +0 -1060
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Container manager WebSocket router.
|
|
3
|
+
*
|
|
4
|
+
* Reading the list, the detail and the logs is open to any signed-in user who
|
|
5
|
+
* can already reach the host; `containers:action` is registered in
|
|
6
|
+
* ADMIN_ONLY_ROUTES, and opening a shell is gated inside the PtyKit server's
|
|
7
|
+
* own `authorize`.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { t } from 'elysia';
|
|
11
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
12
|
+
import { containersListHandler } from './list';
|
|
13
|
+
import { containersActionHandler } from './actions';
|
|
14
|
+
import { containersLogsHandler } from './logs';
|
|
15
|
+
import { containersTunnelHandler } from './tunnel';
|
|
16
|
+
|
|
17
|
+
export const containersRouter = createRouter()
|
|
18
|
+
.merge(containersListHandler)
|
|
19
|
+
.merge(containersActionHandler)
|
|
20
|
+
.merge(containersLogsHandler)
|
|
21
|
+
.merge(containersTunnelHandler)
|
|
22
|
+
// Pushed only when a watched host's list actually changed.
|
|
23
|
+
.emit('containers:changed', t.Object({ result: t.Any() }))
|
|
24
|
+
// The sidebar count: containers running on this machine.
|
|
25
|
+
.emit('containers:badge', t.Object({ count: t.Number() }))
|
|
26
|
+
// A disk reading, pushed to whoever asked when it finally lands. It cannot
|
|
27
|
+
// be a response: `system df` takes as long as the host's disk is large.
|
|
28
|
+
.emit('containers:disk-usage-measured', t.Object({ hostId: t.String(), usage: t.Any() }))
|
|
29
|
+
// A cleanup sweep reaching its end, pushed to everyone attached to it — the
|
|
30
|
+
// dialog that started it may be long closed by then.
|
|
31
|
+
.emit('containers:prune-changed', t.Object({ job: t.Any() }))
|
|
32
|
+
// One coalesced push of container output while a log stream is followed.
|
|
33
|
+
.emit(
|
|
34
|
+
'containers:log-chunk',
|
|
35
|
+
t.Object({
|
|
36
|
+
streamId: t.String(),
|
|
37
|
+
hostId: t.String(),
|
|
38
|
+
containerId: t.String(),
|
|
39
|
+
data: t.String(),
|
|
40
|
+
done: t.Optional(t.Boolean()),
|
|
41
|
+
error: t.Optional(t.Union([t.String(), t.Null()]))
|
|
42
|
+
})
|
|
43
|
+
);
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Containers — reading the list.
|
|
3
|
+
*
|
|
4
|
+
* Watching is per connection: a client asks for a host when it opens that panel
|
|
5
|
+
* and is pushed a fresh listing whenever the host's containers actually change.
|
|
6
|
+
* The watch is torn down when the socket closes, so a browser tab that vanishes
|
|
7
|
+
* cannot leave a host being polled forever.
|
|
8
|
+
*
|
|
9
|
+
* Reading is open to any signed-in user who can already reach the host. Acting
|
|
10
|
+
* on a container is not, and lives in actions.ts.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { t } from 'elysia';
|
|
14
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
15
|
+
import { LOCAL_HOST_ID } from '$shared/types/host';
|
|
16
|
+
import { containerMonitor } from '../../containers/monitor';
|
|
17
|
+
import { inspectContainer, readStats } from '../../containers/actions';
|
|
18
|
+
import { requestDiskUsage } from '../../containers/disk-usage';
|
|
19
|
+
import { stopLogStreamsForUser } from '../../containers/logs';
|
|
20
|
+
import { sshConnectionQueries } from '../../database/queries';
|
|
21
|
+
import { ws } from '../../utils/ws';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* A member may only watch an SSH host they can already reach. The local machine
|
|
25
|
+
* is watchable by anyone signed in — it is the machine they are already using
|
|
26
|
+
* Clopen on.
|
|
27
|
+
*/
|
|
28
|
+
export function requireHostAccess(conn: Parameters<typeof ws.getUserId>[0], hostId: string): void {
|
|
29
|
+
if (hostId === LOCAL_HOST_ID) return;
|
|
30
|
+
const userId = ws.getUserId(conn);
|
|
31
|
+
const isAdmin = ws.getRole(conn) === 'admin';
|
|
32
|
+
sshConnectionQueries.ensureAccess(hostId, userId, isAdmin);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const hostSchema = t.Object({ hostId: t.String({ minLength: 1 }) });
|
|
36
|
+
|
|
37
|
+
export const containersListHandler = createRouter()
|
|
38
|
+
.http('containers:watch', { data: hostSchema, response: t.Any() }, async ({ data, conn }) => {
|
|
39
|
+
requireHostAccess(conn, data.hostId);
|
|
40
|
+
const userId = ws.getUserId(conn);
|
|
41
|
+
|
|
42
|
+
const result = await containerMonitor.watch(data.hostId, userId);
|
|
43
|
+
// The watch belongs to this socket; a reload must not leave it running,
|
|
44
|
+
// and neither must the log streams opened from the same panel.
|
|
45
|
+
ws.addCleanup(conn, () => {
|
|
46
|
+
containerMonitor.unwatch(data.hostId, userId);
|
|
47
|
+
stopLogStreamsForUser(userId);
|
|
48
|
+
});
|
|
49
|
+
return { result };
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
.http('containers:unwatch', { data: hostSchema, response: t.Any() }, async ({ data, conn }) => {
|
|
53
|
+
containerMonitor.unwatch(data.hostId, ws.getUserId(conn));
|
|
54
|
+
return { ok: true };
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The sidebar count, on demand.
|
|
59
|
+
*
|
|
60
|
+
* Pushes only carry changes, so a client that has just loaded — or just
|
|
61
|
+
* reconnected — has no way to learn a count that has been steady. Asking for
|
|
62
|
+
* it is how the badge survives a page refresh instead of reading zero until
|
|
63
|
+
* something happens to move it.
|
|
64
|
+
*/
|
|
65
|
+
.http('containers:summary', { data: t.Object({}), response: t.Any() }, async () => ({
|
|
66
|
+
count: await containerMonitor.refreshBadge()
|
|
67
|
+
}))
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Everything `inspect` knows, read only when a detail pane opens.
|
|
71
|
+
*
|
|
72
|
+
* Environment values are stripped for anyone but an admin. A container's env
|
|
73
|
+
* is where its database password lives, and this panel is reachable by every
|
|
74
|
+
* member and through a shared Remote Access link — so the keys are shown,
|
|
75
|
+
* which is what makes the pane useful, and the values are not.
|
|
76
|
+
*/
|
|
77
|
+
.http(
|
|
78
|
+
'containers:inspect',
|
|
79
|
+
{
|
|
80
|
+
data: t.Object({
|
|
81
|
+
hostId: t.String({ minLength: 1 }),
|
|
82
|
+
containerId: t.String({ minLength: 12 })
|
|
83
|
+
}),
|
|
84
|
+
response: t.Any()
|
|
85
|
+
},
|
|
86
|
+
async ({ data, conn }) => {
|
|
87
|
+
requireHostAccess(conn, data.hostId);
|
|
88
|
+
const detail = await inspectContainer(data.hostId, data.containerId);
|
|
89
|
+
if (!detail || ws.getRole(conn) === 'admin') return { detail, envRedacted: false };
|
|
90
|
+
|
|
91
|
+
return {
|
|
92
|
+
detail: {
|
|
93
|
+
...detail,
|
|
94
|
+
env: detail.env.map((line) => {
|
|
95
|
+
const split = line.indexOf('=');
|
|
96
|
+
return split <= 0 ? line : `${line.slice(0, split)}=`;
|
|
97
|
+
})
|
|
98
|
+
},
|
|
99
|
+
envRedacted: true
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* What the host is holding and how much of it is reclaimable.
|
|
106
|
+
*
|
|
107
|
+
* Read-only, so any member may ask — it is the same `system df` they would
|
|
108
|
+
* run in a terminal, and knowing the disk is full is not a privilege.
|
|
109
|
+
*
|
|
110
|
+
* Returns whatever was last measured, immediately, and reports whether a
|
|
111
|
+
* fresh reading is on its way; that one arrives as
|
|
112
|
+
* `containers:disk-usage-measured`. The measurement cannot be awaited here
|
|
113
|
+
* because its duration is set by how much disk the host holds — see
|
|
114
|
+
* `backend/containers/disk-usage.ts`.
|
|
115
|
+
*/
|
|
116
|
+
.http(
|
|
117
|
+
'containers:disk-usage',
|
|
118
|
+
{
|
|
119
|
+
data: t.Object({
|
|
120
|
+
hostId: t.String({ minLength: 1 }),
|
|
121
|
+
/** The Re-check button: measure again even if the cache is fresh. */
|
|
122
|
+
force: t.Optional(t.Boolean())
|
|
123
|
+
}),
|
|
124
|
+
response: t.Any()
|
|
125
|
+
},
|
|
126
|
+
async ({ data, conn }) => {
|
|
127
|
+
requireHostAccess(conn, data.hostId);
|
|
128
|
+
return requestDiskUsage(data.hostId, ws.getUserId(conn), data.force ?? false);
|
|
129
|
+
}
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
/** One live sample of what a container is consuming, when a pane asks. */
|
|
133
|
+
.http(
|
|
134
|
+
'containers:stats',
|
|
135
|
+
{
|
|
136
|
+
data: t.Object({
|
|
137
|
+
hostId: t.String({ minLength: 1 }),
|
|
138
|
+
containerId: t.String({ minLength: 12 })
|
|
139
|
+
}),
|
|
140
|
+
response: t.Any()
|
|
141
|
+
},
|
|
142
|
+
async ({ data, conn }) => {
|
|
143
|
+
requireHostAccess(conn, data.hostId);
|
|
144
|
+
return { stats: await readStats(data.hostId, data.containerId) };
|
|
145
|
+
}
|
|
146
|
+
);
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Containers — following a container's output.
|
|
3
|
+
*
|
|
4
|
+
* Open to any member who can reach the host: reading a log changes nothing.
|
|
5
|
+
* The stream belongs to the socket that asked for it, so closing the tab stops
|
|
6
|
+
* the `docker logs -f` behind it rather than leaving a process running on
|
|
7
|
+
* someone's machine with nothing listening.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { t } from 'elysia';
|
|
11
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
12
|
+
import { startLogStream, stopLogStream } from '../../containers/logs';
|
|
13
|
+
import { requireHostAccess } from './list';
|
|
14
|
+
import { ws } from '../../utils/ws';
|
|
15
|
+
|
|
16
|
+
export const containersLogsHandler = createRouter()
|
|
17
|
+
.http(
|
|
18
|
+
'containers:logs-start',
|
|
19
|
+
{
|
|
20
|
+
data: t.Object({
|
|
21
|
+
hostId: t.String({ minLength: 1 }),
|
|
22
|
+
containerId: t.String({ minLength: 12 })
|
|
23
|
+
}),
|
|
24
|
+
response: t.Any()
|
|
25
|
+
},
|
|
26
|
+
async ({ data, conn }) => {
|
|
27
|
+
requireHostAccess(conn, data.hostId);
|
|
28
|
+
const userId = ws.getUserId(conn);
|
|
29
|
+
|
|
30
|
+
const started = await startLogStream(data.hostId, data.containerId, userId);
|
|
31
|
+
ws.addCleanup(conn, () => stopLogStream(started.streamId, userId));
|
|
32
|
+
return started;
|
|
33
|
+
}
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
.http(
|
|
37
|
+
'containers:logs-stop',
|
|
38
|
+
{ data: t.Object({ streamId: t.String({ minLength: 1 }) }), response: t.Any() },
|
|
39
|
+
async ({ data, conn }) => {
|
|
40
|
+
stopLogStream(data.streamId, ws.getUserId(conn));
|
|
41
|
+
return { ok: true };
|
|
42
|
+
}
|
|
43
|
+
);
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Containers — the shell tunnel.
|
|
3
|
+
*
|
|
4
|
+
* Mirrors backend/ws/ssh/tunnel.ts: PtyKit's wire protocol rides Clopen's
|
|
5
|
+
* app-wide socket on `containers:pty` / `containers:pty-out`, with one embedded
|
|
6
|
+
* PtyKit connection per Clopen connection.
|
|
7
|
+
*
|
|
8
|
+
* As with the SSH tunnel, the spawn target is stamped here rather than taken
|
|
9
|
+
* from the client. The namespace is the only thing the client says about what
|
|
10
|
+
* it wants, `authorize` has already checked that it may have it, and the target
|
|
11
|
+
* is derived from that same namespace — so naming one container in the
|
|
12
|
+
* namespace and another in the payload cannot open a shell anywhere.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { t } from 'elysia';
|
|
16
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
17
|
+
import type { WSConnection } from '$shared/utils/ws-server';
|
|
18
|
+
import type { PtyKitConnection } from '@myrialabs/ptykit/server';
|
|
19
|
+
import type { WireFrame } from '@myrialabs/ptykit';
|
|
20
|
+
import { ws } from '$backend/utils/ws';
|
|
21
|
+
import { encodeContainerTarget } from '../../containers/pty-backend';
|
|
22
|
+
import { containerPtyKitServer, rememberNamespace, targetFromNamespace } from '../../containers/pty';
|
|
23
|
+
import { debug } from '$shared/utils/logger';
|
|
24
|
+
|
|
25
|
+
/** One embedded PtyKit connection per Clopen ws connection (by stable id). */
|
|
26
|
+
const containerPtyConnections = new Map<string, PtyKitConnection>();
|
|
27
|
+
|
|
28
|
+
function getContainerPtyConnection(conn: WSConnection): PtyKitConnection {
|
|
29
|
+
const connId = ws.getConnectionId(conn);
|
|
30
|
+
if (!connId) {
|
|
31
|
+
throw new Error('Connection not registered');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const existing = containerPtyConnections.get(connId);
|
|
35
|
+
if (existing) return existing;
|
|
36
|
+
|
|
37
|
+
const userId = ws.getUserId(conn);
|
|
38
|
+
const isAdmin = ws.getRole(conn) === 'admin';
|
|
39
|
+
const ptyConn = containerPtyKitServer.createConnection({
|
|
40
|
+
data: { userId, isAdmin, connId },
|
|
41
|
+
send: (frame) => {
|
|
42
|
+
ws.sendToConnectionId(connId, JSON.stringify({ action: 'containers:pty-out', payload: frame }));
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
containerPtyKitServer.handleOpen(ptyConn);
|
|
46
|
+
containerPtyConnections.set(connId, ptyConn);
|
|
47
|
+
|
|
48
|
+
ws.addCleanup(conn, () => {
|
|
49
|
+
containerPtyKitServer.handleClose(ptyConn);
|
|
50
|
+
containerPtyConnections.delete(connId);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
debug.log('containers', `PtyKit connection opened for ${connId}`);
|
|
54
|
+
return ptyConn;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Replace whatever `shell` the client sent with the target derived from the
|
|
59
|
+
* frame's own namespace. Frames that are not `create-session` pass through.
|
|
60
|
+
*/
|
|
61
|
+
function stampSpawnTarget(frame: WireFrame): WireFrame {
|
|
62
|
+
if (frame.action !== 'create-session') return frame;
|
|
63
|
+
|
|
64
|
+
const payload = frame.payload as { requestId?: string; data?: Record<string, unknown> } | null;
|
|
65
|
+
const request = payload?.data;
|
|
66
|
+
if (!request || typeof request.namespace !== 'string') return frame;
|
|
67
|
+
|
|
68
|
+
const target = targetFromNamespace(request.namespace);
|
|
69
|
+
if (!target) return frame;
|
|
70
|
+
rememberNamespace(request.namespace);
|
|
71
|
+
|
|
72
|
+
return {
|
|
73
|
+
action: frame.action,
|
|
74
|
+
payload: { ...payload, data: { ...request, shell: encodeContainerTarget(target) } }
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export const containersTunnelHandler = createRouter()
|
|
79
|
+
// Client → server: one PtyKit wire frame for a container shell.
|
|
80
|
+
.on(
|
|
81
|
+
'containers:pty',
|
|
82
|
+
{
|
|
83
|
+
data: t.Object({
|
|
84
|
+
action: t.String(),
|
|
85
|
+
payload: t.Any()
|
|
86
|
+
})
|
|
87
|
+
},
|
|
88
|
+
({ conn, data }) => {
|
|
89
|
+
const ptyConn = getContainerPtyConnection(conn);
|
|
90
|
+
void containerPtyKitServer.handleFrame(ptyConn, stampSpawnTarget(data as WireFrame));
|
|
91
|
+
}
|
|
92
|
+
)
|
|
93
|
+
// Server → client: PtyKit wire frames. Declared for the typed WSAPI; actually
|
|
94
|
+
// sent via ws.sendToConnectionId above.
|
|
95
|
+
.emit(
|
|
96
|
+
'containers:pty-out',
|
|
97
|
+
t.Object({
|
|
98
|
+
action: t.String(),
|
|
99
|
+
payload: t.Any()
|
|
100
|
+
})
|
|
101
|
+
);
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Panel state is stored one row per (user, project) but must be separated per
|
|
3
|
+
* workspace inside it. Sharing one entry carried open tabs — including unsaved
|
|
4
|
+
* buffers — from the main tree into a worktree, which read as the edit having
|
|
5
|
+
* crossed between them.
|
|
6
|
+
*
|
|
7
|
+
* The envelope logic is what enforces that separation, so it is exercised here
|
|
8
|
+
* against the same shape the handlers read and write.
|
|
9
|
+
*/
|
|
10
|
+
import { describe, expect, test } from 'bun:test';
|
|
11
|
+
|
|
12
|
+
interface ScopedPanelState {
|
|
13
|
+
v: 2;
|
|
14
|
+
scopes: Record<string, string>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function parseStored(raw: string | null): ScopedPanelState {
|
|
18
|
+
if (!raw) return { v: 2, scopes: {} };
|
|
19
|
+
try {
|
|
20
|
+
const parsed = JSON.parse(raw) as ScopedPanelState;
|
|
21
|
+
if (parsed && parsed.v === 2 && typeof parsed.scopes === 'object') return parsed;
|
|
22
|
+
} catch {
|
|
23
|
+
// unparseable → treated as absent
|
|
24
|
+
}
|
|
25
|
+
return { v: 2, scopes: {} };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function isLegacyState(raw: string | null): boolean {
|
|
29
|
+
if (!raw) return false;
|
|
30
|
+
try {
|
|
31
|
+
return (JSON.parse(raw) as { v?: number })?.v !== 2;
|
|
32
|
+
} catch {
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Mirrors files:set-panel-state. */
|
|
38
|
+
function writeScope(raw: string | null, projectId: string, scopeKey: string, state: string | null): string {
|
|
39
|
+
const stored = parseStored(raw);
|
|
40
|
+
if (isLegacyState(raw) && raw) stored.scopes[projectId] = raw;
|
|
41
|
+
if (state === null) delete stored.scopes[scopeKey];
|
|
42
|
+
else stored.scopes[scopeKey] = state;
|
|
43
|
+
return JSON.stringify(stored);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Mirrors files:get-panel-state. */
|
|
47
|
+
function readScope(raw: string | null, projectId: string, scopeKey: string): string | null {
|
|
48
|
+
if (isLegacyState(raw)) return scopeKey === projectId ? raw : null;
|
|
49
|
+
return parseStored(raw).scopes[scopeKey] ?? null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const PROJECT = 'proj-1';
|
|
53
|
+
const MAIN = PROJECT;
|
|
54
|
+
const WORKTREE = 'proj-1~wt-1';
|
|
55
|
+
|
|
56
|
+
describe('files panel state scoping', () => {
|
|
57
|
+
test('a worktree does not see the main tree state', () => {
|
|
58
|
+
const stored = writeScope(null, PROJECT, MAIN, '{"openTabs":["a.ts"]}');
|
|
59
|
+
expect(readScope(stored, PROJECT, MAIN)).toBe('{"openTabs":["a.ts"]}');
|
|
60
|
+
expect(readScope(stored, PROJECT, WORKTREE)).toBeNull();
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('writing one workspace keeps the other', () => {
|
|
64
|
+
let stored = writeScope(null, PROJECT, MAIN, 'main-state');
|
|
65
|
+
stored = writeScope(stored, PROJECT, WORKTREE, 'worktree-state');
|
|
66
|
+
|
|
67
|
+
expect(readScope(stored, PROJECT, MAIN)).toBe('main-state');
|
|
68
|
+
expect(readScope(stored, PROJECT, WORKTREE)).toBe('worktree-state');
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test('two worktrees of one project stay separate', () => {
|
|
72
|
+
const second = 'proj-1~wt-2';
|
|
73
|
+
let stored = writeScope(null, PROJECT, WORKTREE, 'first');
|
|
74
|
+
stored = writeScope(stored, PROJECT, second, 'second');
|
|
75
|
+
|
|
76
|
+
expect(readScope(stored, PROJECT, WORKTREE)).toBe('first');
|
|
77
|
+
expect(readScope(stored, PROJECT, second)).toBe('second');
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test('legacy flat state belongs to the main tree only', () => {
|
|
81
|
+
const legacy = '{"v":1,"openTabs":[]}';
|
|
82
|
+
expect(readScope(legacy, PROJECT, MAIN)).toBe(legacy);
|
|
83
|
+
expect(readScope(legacy, PROJECT, WORKTREE)).toBeNull();
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test('the first worktree write preserves legacy main state', () => {
|
|
87
|
+
const legacy = '{"v":1,"openTabs":[]}';
|
|
88
|
+
const stored = writeScope(legacy, PROJECT, WORKTREE, 'worktree-state');
|
|
89
|
+
|
|
90
|
+
expect(readScope(stored, PROJECT, MAIN)).toBe(legacy);
|
|
91
|
+
expect(readScope(stored, PROJECT, WORKTREE)).toBe('worktree-state');
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test('clearing one workspace leaves the others intact', () => {
|
|
95
|
+
let stored = writeScope(null, PROJECT, MAIN, 'main-state');
|
|
96
|
+
stored = writeScope(stored, PROJECT, WORKTREE, 'worktree-state');
|
|
97
|
+
stored = writeScope(stored, PROJECT, WORKTREE, null);
|
|
98
|
+
|
|
99
|
+
expect(readScope(stored, PROJECT, MAIN)).toBe('main-state');
|
|
100
|
+
expect(readScope(stored, PROJECT, WORKTREE)).toBeNull();
|
|
101
|
+
});
|
|
102
|
+
});
|
|
@@ -27,6 +27,7 @@ const mockGetAllForUser = mock(() => [] as Array<{ id: string; path: string }>);
|
|
|
27
27
|
const mockGetAll = mock(() => [] as Array<{ id: string; path: string }>);
|
|
28
28
|
const mockUserHasProject = mock(() => false);
|
|
29
29
|
const mockGetByPath = mock(() => null as { id: string; path: string } | null);
|
|
30
|
+
const mockGetById = mock(() => null as { id: string; path: string } | null);
|
|
30
31
|
|
|
31
32
|
mock.module('../../database/queries/project-queries', () => ({
|
|
32
33
|
projectQueries: {
|
|
@@ -34,6 +35,19 @@ mock.module('../../database/queries/project-queries', () => ({
|
|
|
34
35
|
getAll: mockGetAll,
|
|
35
36
|
userHasProject: mockUserHasProject,
|
|
36
37
|
getByPath: mockGetByPath,
|
|
38
|
+
getById: mockGetById,
|
|
39
|
+
}
|
|
40
|
+
}));
|
|
41
|
+
|
|
42
|
+
// A project's accessible area now includes its worktrees, so the lookup is part
|
|
43
|
+
// of the data layer this test models.
|
|
44
|
+
const mockWorktreesByProject = mock(() => [] as Array<{ id: string; path: string }>);
|
|
45
|
+
const mockWorktreeByPath = mock(() => null as { id: string; project_id: string; path: string } | null);
|
|
46
|
+
|
|
47
|
+
mock.module('../../database/queries/worktree-queries', () => ({
|
|
48
|
+
worktreeQueries: {
|
|
49
|
+
getByProjectId: mockWorktreesByProject,
|
|
50
|
+
getByPath: mockWorktreeByPath,
|
|
37
51
|
}
|
|
38
52
|
}));
|
|
39
53
|
|
|
@@ -52,7 +66,7 @@ mock.module('../access', () => ({
|
|
|
52
66
|
}));
|
|
53
67
|
|
|
54
68
|
// Import after mocking
|
|
55
|
-
const { requireFilePathAccess, requireSharedFilePathAccess, findContainingProjectId } = await import('./path-access');
|
|
69
|
+
const { requireFilePathAccess, requireSharedFilePathAccess, findContainingProjectId, resolveProjectForRoot, requireWorkspaceRootAccess } = await import('./path-access');
|
|
56
70
|
|
|
57
71
|
let testDir: string;
|
|
58
72
|
|
|
@@ -69,6 +83,84 @@ describe('path-access symlink resolution', () => {
|
|
|
69
83
|
|
|
70
84
|
afterEach(async () => {
|
|
71
85
|
await rm(testDir, { recursive: true, force: true });
|
|
86
|
+
mockWorktreesByProject.mockReturnValue([]);
|
|
87
|
+
mockWorktreeByPath.mockReturnValue(null);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test('allows a path inside a worktree of an accessible project', async () => {
|
|
91
|
+
const projectPath = join(testDir, 'project');
|
|
92
|
+
const worktreePath = join(testDir, 'worktrees', 'feature');
|
|
93
|
+
await mkdir(projectPath, { recursive: true });
|
|
94
|
+
await mkdir(worktreePath, { recursive: true });
|
|
95
|
+
await writeFile(join(worktreePath, 'index.ts'), 'export {};');
|
|
96
|
+
|
|
97
|
+
mockGetAllForUser.mockReturnValue([{ id: 'proj-1', path: projectPath }]);
|
|
98
|
+
mockWorktreesByProject.mockReturnValue([{ id: 'wt-1', path: worktreePath }]);
|
|
99
|
+
|
|
100
|
+
const target = join(worktreePath, 'index.ts');
|
|
101
|
+
await expect(requireFilePathAccess({} as any, target)).resolves.toBe(target);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test('still denies a worktree of a project the user cannot access', async () => {
|
|
105
|
+
const worktreePath = join(testDir, 'worktrees', 'other');
|
|
106
|
+
await mkdir(worktreePath, { recursive: true });
|
|
107
|
+
await writeFile(join(worktreePath, 'secret.txt'), 'nope');
|
|
108
|
+
|
|
109
|
+
mockGetAllForUser.mockReturnValue([]);
|
|
110
|
+
mockWorktreesByProject.mockReturnValue([{ id: 'wt-1', path: worktreePath }]);
|
|
111
|
+
|
|
112
|
+
await expect(
|
|
113
|
+
requireFilePathAccess({} as any, join(worktreePath, 'secret.txt'))
|
|
114
|
+
).rejects.toThrow('Access denied');
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test('resolves a worktree root back to its owning project', async () => {
|
|
118
|
+
const worktreePath = join(testDir, 'worktrees', 'feature');
|
|
119
|
+
mockGetByPath.mockReturnValue(null);
|
|
120
|
+
mockWorktreeByPath.mockReturnValue({ id: 'wt-1', project_id: 'proj-1', path: worktreePath });
|
|
121
|
+
mockGetById.mockReturnValue({ id: 'proj-1', path: join(testDir, 'project') });
|
|
122
|
+
|
|
123
|
+
expect(resolveProjectForRoot(worktreePath)?.id).toBe('proj-1');
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test('returns the worktree root, not the project root, for a worktree path', async () => {
|
|
127
|
+
// The regression this guards: handlers validated the requested root and
|
|
128
|
+
// then operated on `project.path`, so opening a file in a worktree listed
|
|
129
|
+
// and read the main tree instead.
|
|
130
|
+
const projectPath = join(testDir, 'project');
|
|
131
|
+
const worktreePath = join(testDir, 'worktrees', 'feature');
|
|
132
|
+
|
|
133
|
+
mockGetByPath.mockReturnValue(null);
|
|
134
|
+
mockWorktreeByPath.mockReturnValue({ id: 'wt-1', project_id: 'proj-1', path: worktreePath });
|
|
135
|
+
mockGetById.mockReturnValue({ id: 'proj-1', path: projectPath });
|
|
136
|
+
mockGetRole.mockImplementation(() => 'admin');
|
|
137
|
+
|
|
138
|
+
const resolved = requireWorkspaceRootAccess({} as any, worktreePath);
|
|
139
|
+
expect(resolved.root).toBe(worktreePath);
|
|
140
|
+
expect(resolved.worktreeId).toBe('wt-1');
|
|
141
|
+
expect(resolved.project.id).toBe('proj-1');
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
test('returns the project root for the main tree', async () => {
|
|
145
|
+
const projectPath = join(testDir, 'project');
|
|
146
|
+
|
|
147
|
+
mockWorktreeByPath.mockReturnValue(null);
|
|
148
|
+
mockGetByPath.mockReturnValue({ id: 'proj-1', path: projectPath });
|
|
149
|
+
mockGetRole.mockImplementation(() => 'admin');
|
|
150
|
+
|
|
151
|
+
const resolved = requireWorkspaceRootAccess({} as any, projectPath);
|
|
152
|
+
expect(resolved.root).toBe(projectPath);
|
|
153
|
+
expect(resolved.worktreeId).toBeNull();
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
test('denies an unknown root', async () => {
|
|
157
|
+
mockWorktreeByPath.mockReturnValue(null);
|
|
158
|
+
mockGetByPath.mockReturnValue(null);
|
|
159
|
+
mockGetRole.mockImplementation(() => 'admin');
|
|
160
|
+
|
|
161
|
+
expect(() => requireWorkspaceRootAccess({} as any, join(testDir, 'nowhere'))).toThrow(
|
|
162
|
+
'Access denied'
|
|
163
|
+
);
|
|
72
164
|
});
|
|
73
165
|
|
|
74
166
|
test('blocks read through symlink to external directory', async () => {
|
|
@@ -2,6 +2,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:pat
|
|
|
2
2
|
import { realpath } from 'node:fs/promises';
|
|
3
3
|
|
|
4
4
|
import { projectQueries } from '../../database/queries/project-queries';
|
|
5
|
+
import { worktreeQueries } from '../../database/queries/worktree-queries';
|
|
5
6
|
import { ws } from '$backend/utils/ws';
|
|
6
7
|
import type { WSConnection } from '$shared/utils/ws-server';
|
|
7
8
|
import type { Project } from '$shared/types/database/schema';
|
|
@@ -36,15 +37,56 @@ async function isPathInside(rootPath: string, candidatePath: string): Promise<bo
|
|
|
36
37
|
return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel));
|
|
37
38
|
}
|
|
38
39
|
|
|
39
|
-
|
|
40
|
-
|
|
40
|
+
/**
|
|
41
|
+
* Resolve a workspace root to the project that owns it.
|
|
42
|
+
*
|
|
43
|
+
* A worktree root is not a registered project, so a plain project lookup
|
|
44
|
+
* rejects it — which is what made the Files panel deny access to every path
|
|
45
|
+
* inside a worktree.
|
|
46
|
+
*/
|
|
47
|
+
export function resolveProjectForRoot(rootPath: string): Project | null {
|
|
48
|
+
const project = projectQueries.getByPath(rootPath);
|
|
49
|
+
if (project) return project;
|
|
50
|
+
|
|
51
|
+
const worktree = worktreeQueries.getByPath(rootPath);
|
|
52
|
+
if (!worktree) return null;
|
|
53
|
+
|
|
54
|
+
return projectQueries.getById(worktree.project_id);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface WorkspaceRoot {
|
|
58
|
+
/** The project that owns the workspace — what access is decided on. */
|
|
59
|
+
project: Project;
|
|
60
|
+
/** The directory the caller asked for: the project, or one of its worktrees. */
|
|
61
|
+
root: string;
|
|
62
|
+
worktreeId: string | null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Grant access to a workspace root and hand back the root that was requested.
|
|
67
|
+
*
|
|
68
|
+
* Returning the root rather than only the project is the point: callers used to
|
|
69
|
+
* validate a path and then operate on `project.path`, which was identical until
|
|
70
|
+
* worktrees existed and silently became "list the main tree" afterwards.
|
|
71
|
+
*/
|
|
72
|
+
export function requireWorkspaceRootAccess(conn: WSConnection, rootPath: string): WorkspaceRoot {
|
|
73
|
+
const worktree = worktreeQueries.getByPath(rootPath);
|
|
74
|
+
const project = worktree
|
|
75
|
+
? projectQueries.getById(worktree.project_id)
|
|
76
|
+
: projectQueries.getByPath(rootPath);
|
|
77
|
+
|
|
41
78
|
if (!project) {
|
|
42
79
|
throw new Error('Access denied');
|
|
43
80
|
}
|
|
44
|
-
if (ws.getRole(conn)
|
|
45
|
-
|
|
81
|
+
if (ws.getRole(conn) !== 'admin') {
|
|
82
|
+
requireProjectAccess(conn, project.id);
|
|
46
83
|
}
|
|
47
|
-
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
project,
|
|
87
|
+
root: worktree ? worktree.path : project.path,
|
|
88
|
+
worktreeId: worktree?.id ?? null
|
|
89
|
+
};
|
|
48
90
|
}
|
|
49
91
|
|
|
50
92
|
export async function requireFilePathAccess(conn: WSConnection, filePath: string): Promise<string> {
|
|
@@ -65,11 +107,18 @@ export async function requireFilePathAccessFor(filePath: string, role: string |
|
|
|
65
107
|
throw new Error('Access denied');
|
|
66
108
|
}
|
|
67
109
|
|
|
110
|
+
// A project's accessible area is its own tree plus every worktree cloned
|
|
111
|
+
// from it — both are workspaces the user is already entitled to.
|
|
68
112
|
const projects = projectQueries.getAllForUser(userId);
|
|
69
113
|
for (const project of projects) {
|
|
70
114
|
if (await isPathInside(project.path, normalizedPath)) {
|
|
71
115
|
return normalizedPath;
|
|
72
116
|
}
|
|
117
|
+
for (const worktree of worktreeQueries.getByProjectId(project.id)) {
|
|
118
|
+
if (await isPathInside(worktree.path, normalizedPath)) {
|
|
119
|
+
return normalizedPath;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
73
122
|
}
|
|
74
123
|
|
|
75
124
|
throw new Error('Access denied');
|