Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 37 additions & 8 deletions scripts/patch-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,17 @@ var handleUpgrade = (request, bunServer) => {
}
}

// Handle terminal attach WebSocket
if (url.pathname.includes('/api/containers/') && url.pathname.includes('/attach')) {
const pathParts = url.pathname.split('/');
const containerIdIndex = pathParts.indexOf('containers') + 1;
const containerId = pathParts[containerIdIndex];
const envId = url.searchParams.get('envId') ? parseInt(url.searchParams.get('envId'), 10) : undefined;
if (bunServer.upgrade(request, { data: { type: 'terminal', mode: 'attach', containerId, envId } })) {
return new Response(null, { status: 101 });
}
}

// Handle Hawser Edge WebSocket
if (url.pathname === '/api/hawser/connect') {
if (bunServer.upgrade(request, { data: { type: 'hawser' } })) {
Expand Down Expand Up @@ -415,10 +426,11 @@ const combinedWebsocket = {
const connId = 'ws-' + (++_wsConnCounter);
ws.data = ws.data || {};
ws.data.connId = connId;
const { containerId, shell, user, envId } = ws.data;
const { containerId, shell, user, envId, mode } = ws.data;
if (!containerId) { ws.send(JSON.stringify({ type: 'error', message: 'No container ID' })); ws.close(); return; }
const target = await _getDockerTarget(envId);
console.log('[WS] Open:', connId, containerId, 'target:', target.type);
const isAttach = mode === 'attach';
console.log('[WS] Open:', connId, containerId, 'mode:', mode || 'exec', 'target:', target.type);

// Handle Hawser Edge terminal
if (target.type === 'hawser-edge') {
Expand All @@ -427,13 +439,32 @@ const combinedWebsocket = {
const execId = crypto.randomUUID();
_edgeExecSessions.set(execId, { ws, execId, environmentId: target.environmentId });
ws.data.edgeExecId = execId;
conn.ws.send(JSON.stringify({ type: 'exec_start', execId, containerId, cmd: shell || '/bin/sh', user: user || 'root', cols: 120, rows: 30 }));
if (isAttach) {
conn.ws.send(JSON.stringify({ type: 'attach', containerId, attachId: execId }));
} else {
conn.ws.send(JSON.stringify({ type: 'exec_start', execId, containerId, cmd: shell || '/bin/sh', user: user || 'root', cols: 120, rows: 30 }));
}
return;
}

try {
const exec = await createExec(containerId, [shell || '/bin/sh'], user || 'root', target);
const execId = exec.Id;
let execId;
let httpRequest;

if (isAttach) {
// Attach directly to container streams
execId = crypto.randomUUID();
const tokenHeader = target.type === 'tcp' && target.hawserToken ? 'X-Hawser-Token: ' + target.hawserToken + '\\r\\n' : '';
httpRequest = 'POST /containers/' + containerId + '/attach?stream=1&stdout=1&stderr=1&stdin=1 HTTP/1.1\\r\\nHost: localhost\\r\\nContent-Type: application/json\\r\\n' + tokenHeader + 'Connection: Upgrade\\r\\nUpgrade: tcp\\r\\nContent-Length: 0\\r\\n\\r\\n';
} else {
// Create exec instance for shell
const exec = await createExec(containerId, [shell || '/bin/sh'], user || 'root', target);
execId = exec.Id;
const body = JSON.stringify({ Detach: false, Tty: true });
const tokenHeader = target.type === 'tcp' && target.hawserToken ? 'X-Hawser-Token: ' + target.hawserToken + '\\r\\n' : '';
httpRequest = 'POST /exec/' + execId + '/start HTTP/1.1\\r\\nHost: localhost\\r\\nContent-Type: application/json\\r\\n' + tokenHeader + 'Connection: Upgrade\\r\\nUpgrade: tcp\\r\\nContent-Length: ' + body.length + '\\r\\n\\r\\n' + body;
}

let dockerStream;
let headersStripped = false;
let isChunked = false;
Expand All @@ -454,9 +485,7 @@ const combinedWebsocket = {
close() { if (ws.readyState === 1) { ws.send(JSON.stringify({ type: 'exit' })); ws.close(); } },
error() {},
open(socket) {
const body = JSON.stringify({ Detach: false, Tty: true });
const tokenHeader = target.type === 'tcp' && target.hawserToken ? 'X-Hawser-Token: ' + target.hawserToken + '\\r\\n' : '';
socket.write('POST /exec/' + execId + '/start HTTP/1.1\\r\\nHost: localhost\\r\\nContent-Type: application/json\\r\\n' + tokenHeader + 'Connection: Upgrade\\r\\nUpgrade: tcp\\r\\nContent-Length: ' + body.length + '\\r\\n\\r\\n' + body);
socket.write(httpRequest);
}
};
if (target.type === 'unix') {
Expand Down
22 changes: 8 additions & 14 deletions src/lib/data/dependencies.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,6 @@
"license": "MIT",
"repository": "https://github.com/codemirror/autocomplete"
},
{
"name": "@codemirror/commands",
"version": "6.10.0",
"license": "MIT",
"repository": "https://github.com/codemirror/commands"
},
{
"name": "@codemirror/commands",
"version": "6.10.1",
Expand Down Expand Up @@ -157,7 +151,7 @@
},
{
"name": "@lezer/html",
"version": "1.3.12",
"version": "1.3.13",
"license": "MIT",
"repository": "https://github.com/lezer-parser/html"
},
Expand All @@ -175,13 +169,13 @@
},
{
"name": "@lezer/lr",
"version": "1.4.4",
"version": "1.4.7",
"license": "MIT",
"repository": "https://github.com/lezer-parser/lr"
},
{
"name": "@lezer/markdown",
"version": "1.6.1",
"version": "1.6.3",
"license": "MIT",
"repository": "https://github.com/lezer-parser/markdown"
},
Expand Down Expand Up @@ -235,7 +229,7 @@
},
{
"name": "@types/node",
"version": "24.10.1",
"version": "25.0.7",
"license": "MIT",
"repository": "https://github.com/DefinitelyTyped/DefinitelyTyped"
},
Expand Down Expand Up @@ -343,7 +337,7 @@
},
{
"name": "devalue",
"version": "5.5.0",
"version": "5.6.1",
"license": "MIT",
"repository": "https://github.com/sveltejs/devalue"
},
Expand All @@ -355,7 +349,7 @@
},
{
"name": "dockhand",
"version": "1.0.3",
"version": "1.0.7",
"license": "UNLICENSED",
"repository": null
},
Expand Down Expand Up @@ -553,7 +547,7 @@
},
{
"name": "svelte",
"version": "5.46.1",
"version": "5.46.3",
"license": "MIT",
"repository": "https://github.com/sveltejs/svelte"
},
Expand Down Expand Up @@ -589,7 +583,7 @@
},
{
"name": "webidl-conversions",
"version": "8.0.0",
"version": "8.0.1",
"license": "BSD-2-Clause",
"repository": "https://github.com/jsdom/webidl-conversions"
},
Expand Down
22 changes: 21 additions & 1 deletion src/lib/server/docker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export interface ContainerInspectResult {
Hostname: string;
User: string;
Tty: boolean;
OpenStdin: boolean;
Env: string[];
Cmd: string[];
Image: string;
Expand Down Expand Up @@ -661,6 +662,7 @@ export interface ContainerInfo {
mounts: Array<{ type: string; source: string; destination: string; mode: string; rw: boolean }>;
labels: { [key: string]: string };
command: string;
attachable?: boolean
}

export interface ImageInfo {
Expand All @@ -682,6 +684,9 @@ export async function listContainers(all = true, envId?: number | null): Promise
const restartCounts = new Map<string, number>();
const restartingContainers = containers.filter(c => c.State === 'restarting');

const attachableMap = new Map<string, boolean>();
const runningContainers = containers.filter(c => c.State === 'running');

await Promise.all(
restartingContainers.map(async (container) => {
try {
Expand All @@ -693,6 +698,20 @@ export async function listContainers(all = true, envId?: number | null): Promise
})
);

await Promise.all(
runningContainers.map(async (container) => {
try {
const inspect = await inspectContainer(container.Id, envId);

const attachable = (inspect.Config.Tty && inspect.Config.OpenStdin) || false;

attachableMap.set(container.Id, attachable);
} catch (error) {
attachableMap.set(container.Id, false);
}
})
)

return containers.map((container) => {
// Extract network info with IP addresses
const networks: { [networkName: string]: { ipAddress: string } } = {};
Expand Down Expand Up @@ -736,7 +755,8 @@ export async function listContainers(all = true, envId?: number | null): Promise
restartCount: restartCounts.get(container.Id) || 0,
mounts,
labels: container.Labels || {},
command: container.Command || ''
command: container.Command || '',
attachable: attachableMap.get(container.Id) || false
};
});
}
Expand Down
7 changes: 7 additions & 0 deletions src/lib/server/subprocess-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ function getSubprocessPath(name: string): string {
if (existsSync(prodPath)) {
return prodPath;
}

// Local build path - when running built version locally
const localBuildPath = path.join(process.cwd(), 'build', 'subprocesses', `${name}.js`);

if(existsSync(localBuildPath)) {
return localBuildPath;
}
// Development path (relative to this file) - raw TS files
return path.join(__dirname, 'subprocesses', `${name}.ts`);
}
Expand Down
38 changes: 38 additions & 0 deletions src/routes/api/containers/[id]/attach/+server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { authorize } from '$lib/server/authorize';
import { getDockerConnectionInfo } from "$lib/server/docker";
import { json } from "@sveltejs/kit";
import type { RequestHandler } from "./$types";

export const POST: RequestHandler = async ({ params, cookies, url }) => {
const auth = await authorize(cookies);

if (auth.authEnabled && !auth.isAuthenticated) {
return json({ error: "Unauthorized" }, { status: 401 });
}

const containerId = params.id;
const envIdParam = url.searchParams.get("envId");
const envId = envIdParam ? parseInt(envIdParam, 10) : undefined;

// Permission check with environment context
if (!(await auth.can("containers", "attach", envId))) {
return json({ error: "Permission denied" }, { status: 403 });
}

try {
const connectionInfo = await getDockerConnectionInfo(envId);

return json({
containerId,
connectionInfo: {
type: connectionInfo.type,
host: connectionInfo.host,
port: connectionInfo.port,
},
});
} catch (error) {
console.error("Error attaching to container:", error);

return json({ error: "Failed to attach to container" }, { status: 500 });
}
};
Loading