Compare commits

..

No commits in common. "720eade8b518698329aa3cb37cc6b99d2d5fe092" and "cc180562fcd534de7c0890633494cde2c9658d97" have entirely different histories.

47 changed files with 1281 additions and 6622 deletions

View File

@ -10,30 +10,19 @@ on:
paths-ignore: paths-ignore:
- '*.md' - '*.md'
permissions: {}
jobs: jobs:
ci: ci:
name: ${{ matrix.os }}
strategy: strategy:
fail-fast: false
matrix: matrix:
os: [ubuntu-latest, windows-latest, macos-latest] os: [ubuntu-latest, windows-latest, macos-latest, ARM, ARM64]
node: [22] # Can be changed node: [22] # Can be changed
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
timeout-minutes: 30
permissions:
contents: read
steps: steps:
- name: Disable autocrlf - name: Checkout Code
run: | # Mainly for Windows run: | # Mainly for Windows
git config --global core.autocrlf false git config --global core.autocrlf false
git config --global core.eol lf git config --global core.eol lf
- name: Checkout Code
uses: actions/checkout@v4 uses: actions/checkout@v4
with:
persist-credentials: false
- name: Setup Node.js - name: Setup Node.js
uses: actions/setup-node@v3 uses: actions/setup-node@v3
@ -52,3 +41,4 @@ jobs:
- name: Build - name: Build
run: npm run build:frontend run: npm run build:frontend
# more things can be add later like tests etc.. # more things can be add later like tests etc..

View File

@ -81,52 +81,9 @@ curl "https://dockge.kuma.pet/compose.yaml?port=5001&stacksPath=/opt/stacks" --o
- port=`5001` - port=`5001`
- stacksPath=`/opt/stacks` - stacksPath=`/opt/stacks`
Also, once compose is generated/downloaded, add the `PUID` and `PGID` section below to your compose `environment:` section to set stack ownership, otherwise default is `root`
```
# Both PUID and PGID must be set for it to do anything
- PUID=1000 # Set the stack file/dir ownership to this user
- PGID=1000 # Set the stack file/dir ownership to this group
```
Interactive compose.yaml generator is available on: Interactive compose.yaml generator is available on:
https://dockge.kuma.pet https://dockge.kuma.pet
### -OR-
Copy and paste your compose from the following:
If you want to store your stacks in another directory, you can change the `DOCKGE_STACKS_DIR` environment variable and volumes.
compose:
```
services:
dockge:
image: louislam/dockge:1
restart: unless-stopped
ports:
# Host Port:Container Port
- 5001:5001
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./data:/app/data
# If you want to use private registries, you need to share the auth file with Dockge:
# - /root/.docker/:/root/.docker
# Stacks Directory
# Your stacks directory in the host (The paths inside container must be the same as the host)
# ⚠️ If you did it wrong, your data could end up be written into a wrong path.
# ✔️ CORRECT EXAMPLE: - /my-stacks:/my-stacks (Both paths match)
# ❌ WRONG EXAMPLE: - /docker:/my-stacks (Both paths do not match)
- /opt/stacks:/opt/stacks
environment:
# Tell Dockge where your stacks directory is
- DOCKGE_STACKS_DIR=/opt/stacks
# Both PUID and PGID must be set for it to do anything
- PUID=1000 # Set the stack file/dir ownership to this user
- PGID=1000 # Set the stack file/dir ownership to this group
```
## How to Update ## How to Update
```bash ```bash

View File

@ -76,14 +76,12 @@ export class AgentManager {
* @param url * @param url
* @param username * @param username
* @param password * @param password
* @param name
*/ */
async add(url: string, username: string, password: string, name: string): Promise<Agent> { async add(url : string, username : string, password : string) : Promise<Agent> {
let bean = R.dispense("agent") as Agent; let bean = R.dispense("agent") as Agent;
bean.url = url; bean.url = url;
bean.username = username; bean.username = username;
bean.password = password; bean.password = password;
bean.name = name;
await R.store(bean); await R.store(bean);
return bean; return bean;
} }
@ -108,28 +106,7 @@ export class AgentManager {
} }
} }
/**
*
* @param url
* @param updatedName
*/
async update(url: string, updatedName: string) {
const agent = await R.findOne("agent", " url = ? ", [
url,
]);
if (agent) {
agent.name = updatedName;
await R.store(agent);
} else {
throw new Error("Agent not found");
}
}
connect(url : string, username : string, password : string) { connect(url : string, username : string, password : string) {
if (!this.socket.connected) {
return;
}
let obj = new URL(url); let obj = new URL(url);
let endpoint = obj.host; let endpoint = obj.host;
@ -301,8 +278,6 @@ export class AgentManager {
url: "", url: "",
username: "", username: "",
endpoint: "", endpoint: "",
name: "",
updatedName: "",
}; };
for (let endpoint in list) { for (let endpoint in list) {

View File

@ -8,27 +8,10 @@ export class DockerSocketHandler extends AgentSocketHandler {
create(socket : DockgeSocket, server : DockgeServer, agentSocket : AgentSocket) { create(socket : DockgeSocket, server : DockgeServer, agentSocket : AgentSocket) {
// Do not call super.create() // Do not call super.create()
const onStackMutation = (event: string, handler: (...args: unknown[]) => Promise<void>) => { agentSocket.on("deployStack", async (name : unknown, composeYAML : unknown, composeENV : unknown, isAdd : unknown, callback) => {
agentSocket.on(event, async (...args: unknown[]) => {
try { try {
checkLogin(socket); checkLogin(socket);
const name = args[0]; const stack = await this.saveStack(server, name, composeYAML, composeENV, isAdd);
if (typeof name === "string") {
await Stack.withOperation(server, name, () => handler(...args));
} else {
await handler(...args);
}
} catch (error) {
callbackError(error, args.at(-1));
}
});
};
onStackMutation("deployStack", async (name : unknown, composeYAML : unknown, composeENV : unknown, isAdd : unknown, revisionOrCallback, acknowledgement) => {
const callback = typeof revisionOrCallback === "function" ? revisionOrCallback : acknowledgement;
const revision = typeof revisionOrCallback === "function" ? undefined : revisionOrCallback;
try {
const stack = await this.saveStack(server, name, composeYAML, composeENV, isAdd, revision);
await stack.deploy(socket); await stack.deploy(socket);
server.sendStackList(); server.sendStackList();
callbackResult({ callbackResult({
@ -42,16 +25,14 @@ export class DockerSocketHandler extends AgentSocketHandler {
} }
}); });
onStackMutation("saveStack", async (name : unknown, composeYAML : unknown, composeENV : unknown, isAdd : unknown, revisionOrCallback, acknowledgement) => { agentSocket.on("saveStack", async (name : unknown, composeYAML : unknown, composeENV : unknown, isAdd : unknown, callback) => {
const callback = typeof revisionOrCallback === "function" ? revisionOrCallback : acknowledgement;
const revision = typeof revisionOrCallback === "function" ? undefined : revisionOrCallback;
try { try {
const stack = await this.saveStack(server, name, composeYAML, composeENV, isAdd, revision); checkLogin(socket);
await this.saveStack(server, name, composeYAML, composeENV, isAdd);
callbackResult({ callbackResult({
ok: true, ok: true,
msg: "Saved", msg: "Saved",
msgi18n: true, msgi18n: true,
revision: stack.revision,
}, callback); }, callback);
server.sendStackList(); server.sendStackList();
} catch (e) { } catch (e) {
@ -59,8 +40,9 @@ export class DockerSocketHandler extends AgentSocketHandler {
} }
}); });
onStackMutation("deleteStack", async (name : unknown, callback) => { agentSocket.on("deleteStack", async (name : unknown, callback) => {
try { try {
checkLogin(socket);
if (typeof(name) !== "string") { if (typeof(name) !== "string") {
throw new ValidationError("Name must be a string"); throw new ValidationError("Name must be a string");
} }
@ -73,7 +55,6 @@ export class DockerSocketHandler extends AgentSocketHandler {
throw e; throw e;
} }
server.imageVulnerabilityScan.forget(name);
server.sendStackList(); server.sendStackList();
callbackResult({ callbackResult({
ok: true, ok: true,
@ -103,61 +84,12 @@ export class DockerSocketHandler extends AgentSocketHandler {
callbackResult({ callbackResult({
ok: true, ok: true,
stack: await stack.toJSON(socket.endpoint), stack: await stack.toJSON(socket.endpoint),
autoUpdate: await server.stackAutoUpdate.getPolicy(stack),
imageScanSupported: stack.isManagedByDockge,
}, callback); }, callback);
} catch (e) { } catch (e) {
callbackError(e, callback); callbackError(e, callback);
} }
}); });
agentSocket.on("startStackImageScan", async (name, callback) => {
try {
checkLogin(socket);
if (typeof name !== "string" || !/^[a-z0-9_-]+$/.test(name)
|| !await Stack.composeFileExists(server.stacksDir, name)) {
throw new ValidationError("imageScanDiscoveryFailed");
}
const stack = await Stack.getStack(server, name);
callbackResult({
ok: true,
report: server.imageVulnerabilityScan.start(stack),
}, callback);
} catch (error) {
callbackError(error, callback);
}
});
agentSocket.on("getStackImageScan", async (name, callback) => {
try {
checkLogin(socket);
if (typeof name !== "string" || !/^[a-z0-9_-]+$/.test(name)) {
throw new ValidationError("imageScanInvalidRequest");
}
callbackResult({
ok: true,
report: server.imageVulnerabilityScan.summary(name),
}, callback);
} catch (error) {
callbackError(error, callback);
}
});
agentSocket.on("getStackImageFindings", async (name, reportId, imageId, severity, offset, callback) => {
try {
checkLogin(socket);
if (typeof name !== "string" || !/^[a-z0-9_-]+$/.test(name)) {
throw new ValidationError("imageScanInvalidRequest");
}
callbackResult({
ok: true,
...server.imageVulnerabilityScan.page(name, reportId, imageId, severity, offset),
}, callback);
} catch (error) {
callbackError(error, callback);
}
});
// requestStackList // requestStackList
agentSocket.on("requestStackList", async (callback) => { agentSocket.on("requestStackList", async (callback) => {
try { try {
@ -174,8 +106,9 @@ export class DockerSocketHandler extends AgentSocketHandler {
}); });
// startStack // startStack
onStackMutation("startStack", async (stackName : unknown, callback) => { agentSocket.on("startStack", async (stackName : unknown, callback) => {
try { try {
checkLogin(socket);
if (typeof(stackName) !== "string") { if (typeof(stackName) !== "string") {
throw new ValidationError("Stack name must be a string"); throw new ValidationError("Stack name must be a string");
@ -198,8 +131,9 @@ export class DockerSocketHandler extends AgentSocketHandler {
}); });
// stopStack // stopStack
onStackMutation("stopStack", async (stackName : unknown, callback) => { agentSocket.on("stopStack", async (stackName : unknown, callback) => {
try { try {
checkLogin(socket);
if (typeof(stackName) !== "string") { if (typeof(stackName) !== "string") {
throw new ValidationError("Stack name must be a string"); throw new ValidationError("Stack name must be a string");
@ -213,16 +147,15 @@ export class DockerSocketHandler extends AgentSocketHandler {
msgi18n: true, msgi18n: true,
}, callback); }, callback);
server.sendStackList(); server.sendStackList();
stack.leaveCombinedTerminal(socket);
} catch (e) { } catch (e) {
callbackError(e, callback); callbackError(e, callback);
} }
}); });
// restartStack // restartStack
onStackMutation("restartStack", async (stackName : unknown, callback) => { agentSocket.on("restartStack", async (stackName : unknown, callback) => {
try { try {
checkLogin(socket);
if (typeof(stackName) !== "string") { if (typeof(stackName) !== "string") {
throw new ValidationError("Stack name must be a string"); throw new ValidationError("Stack name must be a string");
@ -242,8 +175,9 @@ export class DockerSocketHandler extends AgentSocketHandler {
}); });
// updateStack // updateStack
onStackMutation("updateStack", async (stackName : unknown, callback) => { agentSocket.on("updateStack", async (stackName : unknown, callback) => {
try { try {
checkLogin(socket);
if (typeof(stackName) !== "string") { if (typeof(stackName) !== "string") {
throw new ValidationError("Stack name must be a string"); throw new ValidationError("Stack name must be a string");
@ -263,20 +197,9 @@ export class DockerSocketHandler extends AgentSocketHandler {
}); });
// down stack // down stack
onStackMutation("setStackAutoUpdate", async (name, enabled, callback) => { agentSocket.on("downStack", async (stackName : unknown, callback) => {
if (typeof name !== "string" || !/^[a-z0-9_-]+$/.test(name) || typeof enabled !== "boolean") {
throw new ValidationError("Invalid automatic update settings.");
}
const stack = await Stack.getStack(server, name);
const autoUpdate = await server.stackAutoUpdate.setEnabled(stack, enabled);
callbackResult({
ok: true,
autoUpdate,
}, callback);
});
onStackMutation("downStack", async (stackName : unknown, callback) => {
try { try {
checkLogin(socket);
if (typeof(stackName) !== "string") { if (typeof(stackName) !== "string") {
throw new ValidationError("Stack name must be a string"); throw new ValidationError("Stack name must be a string");
@ -315,81 +238,6 @@ export class DockerSocketHandler extends AgentSocketHandler {
} }
}); });
// Docker stats
agentSocket.on("dockerStats", async (callback) => {
try {
checkLogin(socket);
const dockerStats = Object.fromEntries(await server.getDockerStats());
callbackResult({
ok: true,
dockerStats,
}, callback);
server.sendStackList();
} catch (e) {
callbackError(e, callback);
}
});
// Start a service
onStackMutation("startService", async (stackName: unknown, serviceName: unknown, callback) => {
try {
if (typeof (stackName) !== "string" || typeof (serviceName) !== "string") {
throw new ValidationError("Stack name and service name must be strings");
}
const stack = await Stack.getStack(server, stackName);
await stack.startService(socket, serviceName);
stack.joinCombinedTerminal(socket); // Ensure the combined terminal is joined
callbackResult({
ok: true,
msg: "Service " + serviceName + " started"
}, callback);
server.sendStackList();
} catch (e) {
callbackError(e, callback);
}
});
// Stop a service
onStackMutation("stopService", async (stackName: unknown, serviceName: unknown, callback) => {
try {
if (typeof (stackName) !== "string" || typeof (serviceName) !== "string") {
throw new ValidationError("Stack name and service name must be strings");
}
const stack = await Stack.getStack(server, stackName);
await stack.stopService(socket, serviceName);
callbackResult({
ok: true,
msg: "Service " + serviceName + " stopped"
}, callback);
server.sendStackList();
} catch (e) {
callbackError(e, callback);
}
});
onStackMutation("restartService", async (stackName: unknown, serviceName: unknown, callback) => {
try {
if (typeof stackName !== "string" || typeof serviceName !== "string") {
throw new Error("Invalid stackName or serviceName");
}
const stack = await Stack.getStack(server, stackName, true);
await stack.restartService(socket, serviceName);
callbackResult({
ok: true,
msg: "Service " + serviceName + " restarted"
}, callback);
} catch (e) {
callbackError(e, callback);
}
});
// getExternalNetworkList // getExternalNetworkList
agentSocket.on("getDockerNetworkList", async (callback) => { agentSocket.on("getDockerNetworkList", async (callback) => {
try { try {
@ -405,7 +253,7 @@ export class DockerSocketHandler extends AgentSocketHandler {
}); });
} }
async saveStack(server : DockgeServer, name : unknown, composeYAML : unknown, composeENV : unknown, isAdd : unknown, revision?: unknown) : Promise<Stack> { async saveStack(server : DockgeServer, name : unknown, composeYAML : unknown, composeENV : unknown, isAdd : unknown) : Promise<Stack> {
// Check types // Check types
if (typeof(name) !== "string") { if (typeof(name) !== "string") {
throw new ValidationError("Name must be a string"); throw new ValidationError("Name must be a string");
@ -419,12 +267,9 @@ export class DockerSocketHandler extends AgentSocketHandler {
if (typeof(isAdd) !== "boolean") { if (typeof(isAdd) !== "boolean") {
throw new ValidationError("isAdd must be a boolean"); throw new ValidationError("isAdd must be a boolean");
} }
if (revision !== undefined && (typeof revision !== "string" || !/^[a-f0-9]{64}$/.test(revision))) {
throw new ValidationError("editorConflict");
}
const stack = new Stack(server, name, composeYAML, composeENV, false); const stack = new Stack(server, name, composeYAML, composeENV, false);
await stack.save(isAdd, revision as string | undefined); await stack.save(isAdd);
return stack; return stack;
} }

View File

@ -1,87 +0,0 @@
import { createHash, randomUUID } from "node:crypto";
import jwt from "jsonwebtoken";
import type { Knex } from "knex";
import { R } from "redbean-node";
import { shake256, SHAKE256_LENGTH } from "./password-hash";
const maxTokenAge = 30 * 24 * 60 * 60;
const pending = new Map<string, Promise<void>>();
export interface AuthSession {
fingerprint: string;
expiresAt: number;
}
function sessionFor(token: string, expiresAt: number): AuthSession {
const signedContent = token.slice(0, token.lastIndexOf("."));
return {
fingerprint: createHash("sha256").update(signedContent).digest("hex"),
expiresAt,
};
}
/** Issue a distinct token for each credential login. */
export function issueSession(username: string, passwordHash: string, secret: string) {
const iat = Math.floor(Date.now() / 1000);
const token = jwt.sign({
username,
h: shake256(passwordHash, SHAKE256_LENGTH),
iat,
}, secret, {
algorithm: "HS256",
expiresIn: maxTokenAge,
jwtid: randomUUID(),
});
return {
token,
session: sessionFor(token, iat + maxTokenAge),
};
}
/** Verify signed claims before deriving the identity of a new or legacy token. */
export function verifySession(token: string, secret: string) {
const decoded = jwt.verify(token, secret, {
algorithms: [ "HS256" ],
maxAge: maxTokenAge,
});
if (typeof decoded === "string" || typeof decoded.username !== "string" || typeof decoded.h !== "string"
|| typeof decoded.iat !== "number") {
throw new Error("Invalid session claims");
}
const expiresAt = Math.min(decoded.exp ?? Infinity, decoded.iat + maxTokenAge);
return {
username: decoded.username,
passwordFingerprint: decoded.h,
session: sessionFor(token, expiresAt),
};
}
/** Serialize token login and revocation so that a concurrent login cannot survive logout. */
export async function withSession<T>(session: AuthSession, action: () => Promise<T>): Promise<T> {
const operation = (pending.get(session.fingerprint) ?? Promise.resolve()).then(action);
const tail = operation.then(() => {}, () => {});
pending.set(session.fingerprint, tail);
try {
return await operation;
} finally {
if (pending.get(session.fingerprint) === tail) {
pending.delete(session.fingerprint);
}
}
}
/** Check the persisted revocation before accepting a token. */
export async function isSessionRevoked(session: AuthSession): Promise<boolean> {
return Boolean(await R.knex("revoked_token").where("fingerprint", session.fingerprint).first());
}
/** Persist a revocation and remove records for tokens past their acceptance window. */
export async function revokeSession(session: AuthSession): Promise<void> {
await R.knex.transaction(async (trx: Knex.Transaction) => {
await trx("revoked_token").insert({
fingerprint: session.fingerprint,
expires_at: session.expiresAt,
}).onConflict("fingerprint").ignore();
await trx("revoked_token").where("expires_at", "<=", Math.floor(Date.now() / 1000)).delete();
});
}

View File

@ -37,8 +37,6 @@ import { AgentSocketHandler } from "./agent-socket-handler";
import { AgentSocket } from "../common/agent-socket"; import { AgentSocket } from "../common/agent-socket";
import { ManageAgentSocketHandler } from "./socket-handlers/manage-agent-socket-handler"; import { ManageAgentSocketHandler } from "./socket-handlers/manage-agent-socket-handler";
import { Terminal } from "./terminal"; import { Terminal } from "./terminal";
import { StackAutoUpdate } from "./stack-auto-update";
import { ImageVulnerabilityScan } from "./image-vulnerability-scan";
export class DockgeServer { export class DockgeServer {
app : Express; app : Express;
@ -80,11 +78,7 @@ export class DockgeServer {
jwtSecret : string = ""; jwtSecret : string = "";
private authModeRevision = 0;
stacksDir : string = ""; stacksDir : string = "";
stackAutoUpdate = new StackAutoUpdate(this);
imageVulnerabilityScan = new ImageVulnerabilityScan(this);
/** /**
* *
@ -305,22 +299,21 @@ export class DockgeServer {
// Better do anything after added all socket handlers here // Better do anything after added all socket handlers here
// *************************** // ***************************
log.debug("auth", "check auto login");
if (await Settings.get("disableAuth")) {
log.info("auth", "Disabled Auth: auto login to admin");
this.afterLogin(dockgeSocket, await R.findOne("user") as User);
dockgeSocket.emit("autoLogin");
} else {
log.debug("auth", "need auth");
}
// Socket disconnect // Socket disconnect
dockgeSocket.on("disconnect", () => { dockgeSocket.on("disconnect", () => {
log.info("server", "Socket disconnected!"); log.info("server", "Socket disconnected!");
dockgeSocket.instanceManager.disconnectAll(); dockgeSocket.instanceManager.disconnectAll();
}); });
const authModeRevision = this.authModeRevision;
if (await Settings.get("disableAuth", false)) {
const user = await R.findOne("user", "active = 1") as User | null;
if (user && dockgeSocket.connected && !dockgeSocket.userID && authModeRevision === this.authModeRevision) {
log.info("auth", "Disabled Auth: auto login to admin");
this.afterLogin(dockgeSocket, user, true);
dockgeSocket.emit("autoLogin");
}
}
}); });
this.io.on("disconnect", () => { this.io.on("disconnect", () => {
@ -334,12 +327,8 @@ export class DockgeServer {
} }
} }
async afterLogin(socket : DockgeSocket, user : User, authBypassed = false) { async afterLogin(socket : DockgeSocket, user : User) {
if (!socket.connected) {
return;
}
socket.userID = user.id; socket.userID = user.id;
socket.authBypassed = authBypassed;
socket.join(user.id.toString()); socket.join(user.id.toString());
this.sendInfo(socket); this.sendInfo(socket);
@ -415,7 +404,6 @@ export class DockgeServer {
}); });
checkVersion.startInterval(); checkVersion.startInterval();
this.stackAutoUpdate.start();
}); });
gracefulShutdown(this.httpServer, { gracefulShutdown(this.httpServer, {
@ -423,7 +411,7 @@ export class DockgeServer {
timeout: 30000, // timeout: 30 secs timeout: 30000, // timeout: 30 secs
development: false, // not in dev mode development: false, // not in dev mode
forceExit: true, // triggers process.exit() at the end of shutdown process forceExit: true, // triggers process.exit() at the end of shutdown process
onShutdown: this.shutdownFunction.bind(this), // shutdown function (async) - e.g. for cleanup DB, ... onShutdown: this.shutdownFunction, // shutdown function (async) - e.g. for cleanup DB, ...
finally: this.finalFunction, // finally function (sync) - e.g. for logging finally: this.finalFunction, // finally function (sync) - e.g. for logging
}); });
@ -649,35 +637,6 @@ export class DockgeServer {
return list; return list;
} }
async getDockerStats() : Promise<Map<string, object>> {
let stats = new Map<string, object>();
try {
let res = await childProcessAsync.spawn("docker", [ "stats", "--format", "json", "--no-stream" ], {
encoding: "utf-8",
});
if (!res.stdout) {
return stats;
}
let lines = res.stdout?.toString().split("\n");
for (let line of lines) {
try {
let obj = JSON.parse(line);
stats.set(obj.Name, obj);
} catch (e) {
}
}
return stats;
} catch (e) {
log.error("getDockerStats", e);
return stats;
}
}
get stackDirFullPath() { get stackDirFullPath() {
return path.resolve(this.stacksDir); return path.resolve(this.stacksDir);
} }
@ -693,8 +652,6 @@ export class DockgeServer {
// TODO: Close all terminals? // TODO: Close all terminals?
this.stackAutoUpdate.stop();
await this.imageVulnerabilityScan.stop();
await Database.close(); await Database.close();
Settings.stopCacheCleaner(); Settings.stopCacheCleaner();
} }
@ -726,37 +683,6 @@ export class DockgeServer {
} }
} }
/**
* End sessions admitted while authentication was disabled.
* @returns {void}
*/
revokeBypassedSessions() {
this.authModeRevision++;
for (const rawSocket of this.io.sockets.sockets.values()) {
const socket = rawSocket as DockgeSocket;
if (socket.authBypassed) {
socket.emit("refresh");
socket.disconnect();
}
}
}
/**
* Disconnect other clients that authenticated with the revoked token.
* @param fingerprint Identifier of the revoked token
* @param currentSocketID Socket awaiting its logout acknowledgement
* @returns {void}
*/
disconnectTokenSockets(fingerprint: string, currentSocketID: string) {
for (const rawSocket of this.io.sockets.sockets.values()) {
const socket = rawSocket as DockgeSocket;
if (socket.id !== currentSocketID && socket.authSession?.fingerprint === fingerprint) {
socket.emit("sessionRevoked");
socket.disconnect();
}
}
}
isSSL() { isSSL() {
return this.config.sslKey && this.config.sslCert; return this.config.sslKey && this.config.sslCert;
} }

View File

@ -1,436 +0,0 @@
import { execFile, spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { createWriteStream, promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import { promisify } from "node:util";
import type { DockgeServer } from "./dockge-server";
import { log } from "./log";
import type { Stack } from "./stack";
import { ValidationError } from "./util-server";
const exec = promisify(execFile);
const severities = [ "critical", "high", "medium", "low", "negligible", "unknown" ] as const;
type Severity = typeof severities[number];
const maxImageBytes = 1024 * 1024 * 1024;
const maxImages = 20;
const maxReports = 8;
const maxFindings = 500;
const pageSize = 25;
const imageIdPattern = /^sha256:[a-f0-9]{64}$/;
const inspectFields = [
"\"id\":{{json .Image}}",
"\"reference\":{{json .Config.Image}}",
"\"service\":{{json (index .Config.Labels \"com.docker.compose.service\")}}",
"\"directory\":{{json (index .Config.Labels \"com.docker.compose.project.working_dir\")}}",
"\"oneOff\":{{json (index .Config.Labels \"com.docker.compose.oneoff\")}}",
];
const inspectFormat = `{${inspectFields.join(",")}}`;
interface Finding {
id: string;
namespace: string;
severity: Severity;
packageName: string;
packageType: string;
installedVersion: string;
fixedVersions: string[];
}
interface ImageScan {
id: string;
references: string[];
services: string[];
status: "pending" | "scanned" | "failed";
counts?: Record<Severity, number>;
error?: string;
truncated?: boolean;
scannerVersion?: string;
databaseBuiltAt?: string;
findings: Finding[];
}
interface ScanReport {
id: string;
stackName: string;
status: "running" | "complete" | "failed";
startedAt: string;
finishedAt?: string;
error?: string;
images: ImageScan[];
}
interface GrypeMatch {
vulnerability?: {
id?: string;
namespace?: string;
severity?: string;
fix?: { versions?: string[] };
};
artifact?: { name?: string; type?: string; version?: string };
}
interface ContainerImage {
id: string;
reference: string;
service: string;
directory: string;
oneOff: string;
}
/** Limit strings forwarded from third-party reports to the browser. */
function label(value: unknown, length = 160): string {
if (typeof value !== "string") {
return "";
}
return value.length > length ? value.slice(0, length - 1) + "…" : value;
}
/** Normalize scanner output while keeping the original severity and package identity. */
function normalizeFindings(output: string) {
const report = JSON.parse(output) as {
matches?: GrypeMatch[];
descriptor?: {
version?: string;
db?: { status?: { built?: string; valid?: boolean } };
};
};
if (!Array.isArray(report?.matches)) {
throw new ValidationError("imageScanInvalidReport");
}
if (report.descriptor?.db?.status?.valid === false) {
throw new ValidationError("imageScanInvalidReport");
}
const counts: Record<Severity, number> = {
critical: 0,
high: 0,
medium: 0,
low: 0,
negligible: 0,
unknown: 0,
};
const unique = new Map<string, Finding>();
for (const match of report.matches) {
const id = label(match?.vulnerability?.id, 80);
const packageName = label(match?.artifact?.name);
if (!id || !packageName) {
continue;
}
const reportedSeverity = label(match.vulnerability?.severity).toLowerCase();
const severity = severities.find(value => value === reportedSeverity) ?? "unknown";
const versions = match.vulnerability?.fix?.versions;
const finding: Finding = {
id,
packageName,
namespace: label(match.vulnerability?.namespace),
severity,
packageType: label(match.artifact?.type, 40),
installedVersion: label(match.artifact?.version),
fixedVersions: Array.isArray(versions) ? versions.slice(0, 10).map(version => label(version)).filter(Boolean) : [],
};
const key = JSON.stringify([
match.vulnerability?.id,
match.vulnerability?.namespace,
match.artifact?.name,
match.artifact?.type,
match.artifact?.version,
]);
if (!unique.has(key)) {
unique.set(key, finding);
counts[severity]++;
}
}
const findings = Array.from(unique.values()).sort((a, b) => severities.indexOf(a.severity) - severities.indexOf(b.severity)
|| a.id.localeCompare(b.id) || a.packageName.localeCompare(b.packageName));
const databaseBuiltAt = report.descriptor?.db?.status?.built;
return {
counts,
truncated: findings.length > maxFindings,
findings: findings.slice(0, maxFindings),
scannerVersion: label(report.descriptor?.version, 40),
databaseBuiltAt: typeof databaseBuiltAt === "string" && Number.isFinite(Date.parse(databaseBuiltAt)) ? databaseBuiltAt : undefined,
};
}
export class ImageVulnerabilityScan {
private readonly scanner = process.env.DOCKGE_GRYPE_PATH || "grype";
private readonly reports = new Map<string, ScanReport>();
private readonly shutdown = new AbortController();
private active?: ScanReport;
private activeRun?: Promise<void>;
constructor(private readonly server: DockgeServer) {}
/** Start one bounded scan per host without waiting for Docker or Grype to finish. */
start(stack: Stack) {
if (this.active) {
if (this.active.stackName === stack.name && this.reports.has(stack.name)) {
return this.summary(stack.name);
}
throw new ValidationError("imageScanHostBusy");
}
const report: ScanReport = {
id: randomUUID(),
stackName: stack.name,
status: "running",
startedAt: new Date().toISOString(),
images: [],
};
this.reports.delete(stack.name);
this.reports.set(stack.name, report);
const oldest = this.reports.keys().next().value;
if (this.reports.size > maxReports && oldest !== undefined) {
this.reports.delete(oldest);
}
this.active = report;
this.activeRun = this.run(stack, report);
return this.summary(stack.name);
}
/** Return progress and counts without sending package details over the socket. */
summary(stackName: string) {
const report = this.reports.get(stackName);
if (!report) {
return null;
}
return {
...report,
images: report.images.map(({ findings, ...image }) => image),
};
}
/** Page through retained findings for the requested immutable image and report. */
page(stackName: string, reportId: unknown, imageId: unknown, severity: unknown, offset: unknown) {
if (typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 0 || offset > maxFindings
|| (severity !== "" && !severities.some(value => value === severity))) {
throw new ValidationError("imageScanInvalidRequest");
}
const report = this.reports.get(stackName);
if (!report || report.id !== reportId) {
throw new ValidationError("imageScanReportChanged");
}
const image = report.images.find(item => item.id === imageId && item.status === "scanned");
if (!image) {
throw new ValidationError("imageScanReportChanged");
}
const findings = severity ? image.findings.filter(item => item.severity === severity) : image.findings;
return {
rows: findings.slice(offset, offset + pageSize),
total: findings.length,
pageSize,
};
}
/** Forget reports for a deleted stack, including one still being scanned. */
forget(stackName: string) {
this.reports.delete(stackName);
}
/** Abort outstanding commands as Dockge shuts down. */
async stop() {
this.shutdown.abort();
await this.activeRun;
}
/** Scan each immutable image once and keep the successful partial results. */
private async run(stack: Stack, report: ScanReport) {
try {
report.images = await this.discoverImages(stack);
if (report.images.length) {
await this.runGrype([ "version" ], path.resolve(this.server.config.dataDir), 5000);
}
for (const image of report.images) {
if (this.shutdown.signal.aborted) {
break;
}
try {
Object.assign(image, await this.scanImage(stack, image.id));
image.status = "scanned";
} catch (error) {
image.status = "failed";
image.error = this.reportError(error, "imageScanImageFailed");
}
}
report.status = "complete";
} catch (error) {
report.status = "failed";
report.error = this.reportError(error, "imageScanFailed");
} finally {
report.finishedAt = new Date().toISOString();
this.active = undefined;
}
}
/** Discover the images actually attached to this stack's running or stopped containers. */
private async discoverImages(stack: Stack): Promise<ImageScan[]> {
const cwd = path.resolve(stack.path);
const output = await this.docker(stack, stack.getComposeOptions("ps", "--all", "--orphans=false", "--quiet"));
const ids = output ? output.split(/\r?\n/) : [];
if (!ids.length) {
return [];
}
if (ids.length > 500 || !ids.every(id => /^[a-f0-9]{12,64}$/.test(id))) {
throw new ValidationError("imageScanDiscoveryFailed");
}
const inspected = await this.docker(stack, [ "container", "inspect", "--format", inspectFormat, "--", ...ids ]);
const images = new Map<string, ImageScan>();
const containers = inspected.split(/\r?\n/).map(line => JSON.parse(line) as ContainerImage);
if (containers.length !== ids.length) {
throw new ValidationError("imageScanDiscoveryFailed");
}
for (const container of containers) {
if (container.oneOff?.toLowerCase() !== "false" || !container.directory || path.resolve(container.directory) !== cwd) {
continue;
}
if (!imageIdPattern.test(container.id)) {
throw new ValidationError("imageScanDiscoveryFailed");
}
let image = images.get(container.id);
if (!image) {
image = {
id: container.id,
references: [],
services: [],
status: "pending",
findings: [],
};
images.set(container.id, image);
}
const reference = label(container.reference);
const service = label(container.service);
if (reference && image.references.length < 20 && !image.references.includes(reference)) {
image.references.push(reference);
}
if (service && image.services.length < 20 && !image.services.includes(service)) {
image.services.push(service);
}
}
if (images.size > maxImages) {
throw new ValidationError("imageScanTooManyImages");
}
return Array.from(images.values());
}
/** Export only the immutable local image and remove the archive on every exit path. */
private async scanImage(stack: Stack, id: string) {
const size = Number(await this.docker(stack, [ "image", "inspect", "--format", "{{.Size}}", "--", id ]));
if (!Number.isSafeInteger(size) || size < 0 || size > maxImageBytes) {
throw new ValidationError("imageScanImageTooLarge");
}
const directory = await fs.mkdtemp(path.join(os.tmpdir(), "dockge-image-scan-"));
try {
const archive = path.join(directory, "image.tar");
await this.saveImage(stack, id, archive);
const stdout = await this.runGrype([ `docker-archive:${archive}`, "-o", "json" ], directory, 5 * 60 * 1000);
try {
return normalizeFindings(stdout);
} catch {
throw new ValidationError("imageScanInvalidReport");
}
} finally {
await fs.rm(directory, {
recursive: true,
force: true,
});
}
}
/** Stream Docker's export to disk with a hard archive limit and a timeout. */
private async saveImage(stack: Stack, id: string, archive: string) {
let bytes = 0;
const limit = new Transform({
transform(chunk, encoding, callback) {
bytes += chunk.length;
if (bytes > maxImageBytes) {
callback(new ValidationError("imageScanImageTooLarge"));
} else {
callback(null, chunk);
}
},
});
const child = spawn("docker", [ "image", "save", "--", id ], {
cwd: stack.path,
stdio: [ "ignore", "pipe", "ignore" ],
timeout: 120000,
signal: this.shutdown.signal,
windowsHide: true,
});
const exited = new Promise<void>((resolve, reject) => {
child.once("error", reject);
child.once("close", code => {
if (code === 0) {
resolve();
} else {
reject(new ValidationError("imageScanExportFailed"));
}
});
});
try {
await Promise.all([ pipeline(child.stdout, limit, createWriteStream(archive, { flags: "wx",
mode: 0o600 })), exited ]);
} finally {
if (child.exitCode === null && child.signalCode === null) {
child.kill();
}
await exited.catch(() => {});
}
}
/** Run Docker without exposing raw CLI errors to the browser. */
private async docker(stack: Stack, args: string[]): Promise<string> {
const { stdout } = await exec("docker", args, {
cwd: stack.path,
timeout: 30000,
maxBuffer: 2 * 1024 * 1024,
signal: this.shutdown.signal,
windowsHide: true,
});
return stdout.trim();
}
/** Invoke a local Grype binary against an archive, with a persistent DB cache. */
private async runGrype(args: string[], cwd: string, timeout: number): Promise<string> {
try {
const { stdout } = await exec(this.scanner, args, {
cwd,
timeout,
maxBuffer: 32 * 1024 * 1024,
signal: this.shutdown.signal,
windowsHide: true,
env: {
...process.env,
GRYPE_DB_CACHE_DIR: path.resolve(this.server.config.dataDir, "grype-db"),
GRYPE_CHECK_FOR_APP_UPDATE: "false",
TMPDIR: cwd,
TMP: cwd,
TEMP: cwd,
},
});
return stdout;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
throw new ValidationError("imageScanScannerUnavailable");
}
throw error;
}
}
/** Keep CLI output and filesystem paths out of the UI and diagnostic logs. */
private reportError(error: unknown, fallback: string): string {
if (this.shutdown.signal.aborted) {
return fallback;
}
if (error instanceof ValidationError) {
return error.message;
}
const code = (error as NodeJS.ErrnoException)?.code ?? "unknown";
log.warn("image-scan", `${fallback} (${code})`);
return fallback;
}
}

View File

@ -7,7 +7,6 @@ export async function up(knex: Knex): Promise<void> {
table.string("url", 255).notNullable().unique(); table.string("url", 255).notNullable().unique();
table.string("username", 255).notNullable(); table.string("username", 255).notNullable();
table.string("password", 255).notNullable(); table.string("password", 255).notNullable();
table.string("name", 255);
table.boolean("active").notNullable().defaultTo(true); table.boolean("active").notNullable().defaultTo(true);
}); });
} }

View File

@ -1,12 +0,0 @@
import { Knex } from "knex";
export async function up(knex: Knex): Promise<void> {
await knex.schema.createTable("revoked_token", (table) => {
table.string("fingerprint", 64).primary();
table.bigInteger("expires_at").notNullable().index();
});
}
export async function down(knex: Knex): Promise<void> {
await knex.schema.dropTable("revoked_token");
}

View File

@ -23,7 +23,6 @@ export class Agent extends BeanModel {
url: this.url, url: this.url,
username: this.username, username: this.username,
endpoint: this.endpoint, endpoint: this.endpoint,
name: this.name,
}; };
} }

View File

@ -1,6 +1,7 @@
import jwt from "jsonwebtoken";
import { R } from "redbean-node"; import { R } from "redbean-node";
import { BeanModel } from "redbean-node/dist/bean-model"; import { BeanModel } from "redbean-node/dist/bean-model";
import { generatePasswordHash } from "../password-hash"; import { generatePasswordHash, shake256, SHAKE256_LENGTH } from "../password-hash";
export class User extends BeanModel { export class User extends BeanModel {
/** /**
@ -26,6 +27,20 @@ export class User extends BeanModel {
await User.resetPassword(this.id, newPassword); await User.resetPassword(this.id, newPassword);
this.password = newPassword; this.password = newPassword;
} }
/**
* Create a new JWT for a user
* @param {User} user The User to create a JsonWebToken for
* @param {string} jwtSecret The key used to sign the JsonWebToken
* @returns {string} the JsonWebToken as a string
*/
static createJWT(user : User, jwtSecret : string) {
return jwt.sign({
username: user.username,
h: shake256(user.password, SHAKE256_LENGTH),
}, jwtSecret);
}
} }
export default User; export default User;

View File

@ -26,10 +26,9 @@ export class Settings {
/** /**
* Retrieve value of setting based on key * Retrieve value of setting based on key
* @param key Key of setting to retrieve * @param key Key of setting to retrieve
* @param useCache Whether to read and populate the settings cache
* @returns Value * @returns Value
*/ */
static async get(key : string, useCache = true) { static async get(key : string) {
// Start cache clear if not started yet // Start cache clear if not started yet
if (!Settings.cacheCleaner) { if (!Settings.cacheCleaner) {
@ -46,7 +45,7 @@ export class Settings {
} }
// Query from cache // Query from cache
if (useCache && key in Settings.cacheList) { if (key in Settings.cacheList) {
const v = Settings.cacheList[key].value; const v = Settings.cacheList[key].value;
log.debug("settings", `Get Setting (cache): ${key}: ${v}`); log.debug("settings", `Get Setting (cache): ${key}: ${v}`);
return v; return v;
@ -60,12 +59,10 @@ export class Settings {
const v = JSON.parse(value); const v = JSON.parse(value);
log.debug("settings", `Get Setting: ${key}: ${v}`); log.debug("settings", `Get Setting: ${key}: ${v}`);
if (useCache) {
Settings.cacheList[key] = { Settings.cacheList[key] = {
value: v, value: v,
timestamp: Date.now() timestamp: Date.now()
}; };
}
return v; return v;
} catch (e) { } catch (e) {

View File

@ -1,7 +1,7 @@
import { SocketHandler } from "../socket-handler.js"; import { SocketHandler } from "../socket-handler.js";
import { DockgeServer } from "../dockge-server"; import { DockgeServer } from "../dockge-server";
import { log } from "../log"; import { log } from "../log";
import { callbackError, checkLogin, DockgeSocket } from "../util-server"; import { checkLogin, DockgeSocket } from "../util-server";
import { AgentSocket } from "../../common/agent-socket"; import { AgentSocket } from "../../common/agent-socket";
import { ALL_ENDPOINTS } from "../../common/util-common"; import { ALL_ENDPOINTS } from "../../common/util-common";
@ -37,10 +37,6 @@ export class AgentProxySocketHandler extends SocketHandler {
if (e instanceof Error) { if (e instanceof Error) {
log.warn("agent", e.message); log.warn("agent", e.message);
} }
const callback = args.at(-1);
if (typeof callback === "function") {
callbackError(e, callback);
}
} }
}); });
} }

View File

@ -12,10 +12,11 @@ import {
checkLogin, checkLogin,
DockgeSocket, DockgeSocket,
doubleCheckPassword, doubleCheckPassword,
JWTDecoded,
ValidationError ValidationError
} from "../util-server"; } from "../util-server";
import { passwordStrength } from "check-password-strength"; import { passwordStrength } from "check-password-strength";
import { isSessionRevoked, issueSession, revokeSession, verifySession, withSession } from "../auth-session"; import jwt from "jsonwebtoken";
import { Settings } from "../settings"; import { Settings } from "../settings";
import fs, { promises as fsAsync } from "fs"; import fs, { promises as fsAsync } from "fs";
import path from "path"; import path from "path";
@ -63,47 +64,44 @@ export class MainSocketHandler extends SocketHandler {
// Login by token // Login by token
socket.on("loginByToken", async (token, callback) => { socket.on("loginByToken", async (token, callback) => {
if (typeof callback !== "function") {
return;
}
const clientIP = await server.getClientIP(socket); const clientIP = await server.getClientIP(socket);
log.info("auth", `Login by token. IP=${clientIP}`); log.info("auth", `Login by token. IP=${clientIP}`);
try { try {
const { username, passwordFingerprint, session } = verifySession(token, server.jwtSecret); const decoded = jwt.verify(token, server.jwtSecret) as JWTDecoded;
log.info("auth", "Username from JWT: " + username); log.info("auth", "Username from JWT: " + decoded.username);
await withSession(session, async () => { const user = await R.findOne("user", " username = ? AND active = 1 ", [
if (await isSessionRevoked(session)) { decoded.username,
throw new Error("Session token has been revoked"); ]) as User;
if (user) {
// Check if the password changed
if (decoded.h !== shake256(user.password, SHAKE256_LENGTH)) {
throw new Error("The token is invalid due to password change or old token");
} }
const user = await R.findOne("user", " username = ? AND active = 1 ", [ username ]) as User | null;
if (!user) { log.debug("auth", "afterLogin");
log.info("auth", `Inactive or deleted user ${username}. IP=${clientIP}`); await server.afterLogin(socket, user);
log.debug("auth", "afterLogin ok");
log.info("auth", `Successfully logged in user ${decoded.username}. IP=${clientIP}`);
callback({
ok: true,
});
} else {
log.info("auth", `Inactive or deleted user ${decoded.username}. IP=${clientIP}`);
callback({ callback({
ok: false, ok: false,
msg: "authUserInactiveOrDeleted", msg: "authUserInactiveOrDeleted",
msgi18n: true, msgi18n: true,
}); });
return;
} }
// Check if the password changed
if (passwordFingerprint !== shake256(user.password, SHAKE256_LENGTH)) {
throw new Error("The token is invalid due to password change or old token");
}
if (session.expiresAt <= Math.floor(Date.now() / 1000)) {
throw new Error("Session token has expired");
}
if (!socket.connected) {
return;
}
socket.authSession = session;
await server.afterLogin(socket, user);
log.info("auth", `Successfully logged in user ${username}. IP=${clientIP}`);
callback({ ok: true });
});
} catch (error) { } catch (error) {
if (!(error instanceof Error)) { if (!(error instanceof Error)) {
console.error("Unknown error:", error); console.error("Unknown error:", error);
@ -147,13 +145,14 @@ export class MainSocketHandler extends SocketHandler {
if (user) { if (user) {
if (user.twofa_status === 0) { if (user.twofa_status === 0) {
server.afterLogin(socket, user);
log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`); log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`);
callback({ callback({
ok: true, ok: true,
token: this.startSession(socket, server, user), token: User.createJWT(user, server.jwtSecret),
}); });
return;
} }
if (user.twofa_status === 1 && !data.token) { if (user.twofa_status === 1 && !data.token) {
@ -170,16 +169,18 @@ export class MainSocketHandler extends SocketHandler {
const verify = notp.totp.verify(data.token, user.twofa_secret, twoFAVerifyOptions); const verify = notp.totp.verify(data.token, user.twofa_secret, twoFAVerifyOptions);
if (user.twofa_last_token !== data.token && verify) { if (user.twofa_last_token !== data.token && verify) {
server.afterLogin(socket, user);
await R.exec("UPDATE `user` SET twofa_last_token = ? WHERE id = ? ", [ await R.exec("UPDATE `user` SET twofa_last_token = ? WHERE id = ? ", [
data.token, data.token,
user.id, socket.userID,
]); ]);
log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`); log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`);
callback({ callback({
ok: true, ok: true,
token: this.startSession(socket, server, user), token: User.createJWT(user, server.jwtSecret),
}); });
} else { } else {
@ -205,32 +206,6 @@ export class MainSocketHandler extends SocketHandler {
}); });
socket.on("logout", async (callback) => {
try {
checkLogin(socket);
const session = socket.authSession;
if (session) {
await withSession(session, async () => {
await revokeSession(session);
server.disconnectTokenSockets(session.fingerprint, socket.id);
});
}
if (typeof callback === "function") {
callback({ ok: true });
}
socket.disconnect();
} catch (error) {
log.error("auth", error);
if (typeof callback === "function") {
callback({
ok: false,
msg: "authLogoutFailed",
msgi18n: true,
});
}
}
});
// Change Password // Change Password
socket.on("changePassword", async (password, callback) => { socket.on("changePassword", async (password, callback) => {
try { try {
@ -291,28 +266,18 @@ export class MainSocketHandler extends SocketHandler {
}); });
socket.on("setSettings", async (data, currentPassword, callback) => { socket.on("setSettings", async (data, currentPassword, callback) => {
if (typeof callback !== "function") {
return;
}
try { try {
checkLogin(socket); checkLogin(socket);
let disableAuth = data.disableAuth; // If currently is disabled auth, don't need to check
if (Object.hasOwn(data, "disableAuth") && typeof disableAuth !== "boolean") { // Disabled Auth + Want to Disable Auth => No Check
throw new ValidationError("Invalid authentication setting."); // Disabled Auth + Want to Enable Auth => No Check
} // Enabled Auth + Want to Disable Auth => Check!!
delete data.disableAuth; // Enabled Auth + Want to Enable Auth => No Check
if (disableAuth === true) { const currentDisabledAuth = await Settings.get("disableAuth");
if (await Settings.get("disableAuth", false)) { if (!currentDisabledAuth && data.disableAuth) {
// Older clients include the current flag when saving unrelated settings.
disableAuth = undefined;
} else {
await doubleCheckPassword(socket, currentPassword); await doubleCheckPassword(socket, currentPassword);
} }
}
if (!socket.connected) {
throw new Error("You are not logged in.");
}
// Handle global.env // Handle global.env
if (data.globalENV && data.globalENV != "# VARIABLE=value #comment") { if (data.globalENV && data.globalENV != "# VARIABLE=value #comment") {
await fsAsync.writeFile(path.join(server.stacksDir, "global.env"), data.globalENV); await fsAsync.writeFile(path.join(server.stacksDir, "global.env"), data.globalENV);
@ -326,24 +291,12 @@ export class MainSocketHandler extends SocketHandler {
await Settings.setSettings("general", data); await Settings.setSettings("general", data);
if (typeof disableAuth === "boolean") {
if (!socket.connected) {
throw new Error("You are not logged in.");
}
await Settings.set("disableAuth", disableAuth, "general");
}
callback({ callback({
ok: true, ok: true,
msg: "Saved" msg: "Saved"
}); });
if (disableAuth === false) {
server.revokeBypassedSessions();
}
if (socket.connected) {
server.sendInfo(socket); server.sendInfo(socket);
}
} catch (e) { } catch (e) {
if (e instanceof Error) { if (e instanceof Error) {
@ -392,20 +345,6 @@ export class MainSocketHandler extends SocketHandler {
}); });
} }
/**
* Attach the new token identity to the connection before returning the token.
* @param socket Connection being authenticated
* @param server Dockge instance issuing the token
* @param user Authenticated user
* @returns The signed JWT
*/
private startSession(socket: DockgeSocket, server: DockgeServer, user: User): string {
const { token, session } = issueSession(user.username, user.password, server.jwtSecret);
socket.authSession = session;
server.afterLogin(socket, user);
return token;
}
async login(username : string, password : string) : Promise<User | null> { async login(username : string, password : string) : Promise<User | null> {
if (typeof username !== "string" || typeof password !== "string") { if (typeof username !== "string" || typeof password !== "string") {
return null; return null;

View File

@ -20,7 +20,7 @@ export class ManageAgentSocketHandler extends SocketHandler {
let data = requestData as LooseObject; let data = requestData as LooseObject;
let manager = socket.instanceManager; let manager = socket.instanceManager;
await manager.test(data.url, data.username, data.password); await manager.test(data.url, data.username, data.password);
await manager.add(data.url, data.username, data.password, data.name); await manager.add(data.url, data.username, data.password);
// connect to the agent // connect to the agent
manager.connect(data.url, data.username, data.password); manager.connect(data.url, data.username, data.password);
@ -66,27 +66,5 @@ export class ManageAgentSocketHandler extends SocketHandler {
callbackError(e, callback); callbackError(e, callback);
} }
}); });
// updateAgent
socket.on("updateAgent", async (name : string, updatedName : string, callback : unknown) => {
try {
log.debug("manage-agent-socket-handler", "updateAgent");
checkLogin(socket);
let manager = socket.instanceManager;
await manager.update(name, updatedName);
server.disconnectAllSocketClients(undefined, socket.id);
manager.sendAgentList();
callbackResult({
ok: true,
msg: "agentUpdatedSuccessfully",
msgi18n: true,
}, callback);
} catch (e) {
callbackError(e, callback);
}
});
} }
} }

View File

@ -1,337 +0,0 @@
import { execFile } from "node:child_process";
import { randomUUID } from "node:crypto";
import { promises as fs } from "node:fs";
import { hostname } from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { Cron } from "croner";
import type { DockgeServer } from "./dockge-server";
import { log } from "./log";
import { Stack } from "./stack";
import { ValidationError } from "./util-server";
const exec = promisify(execFile);
const policyFile = ".dockge-auto-update.json";
const dockgeImage = /(?:^|\/)louislam\/dockge(?:[:@]|$)/i;
const stackName = /^[a-z0-9_-]+$/;
type Outcome = "updated" | "unchanged" | "skipped" | "failed";
const outcomes: Outcome[] = [ "updated", "unchanged", "skipped", "failed" ];
interface Policy {
enabled: boolean;
lastRun?: {
at: string;
result: Outcome;
};
}
interface ContainerSummary {
ID: string;
Service: string;
State: string;
}
interface ContainerDetails {
image: string;
hash: string;
directory: string;
oneOff: string;
}
interface Candidate {
image: string;
hash: string;
containers: string[];
imageIds: string[];
}
interface ComposeConfig {
name: string;
services: Record<string, { image?: string; build?: unknown; platform?: string; pull_policy?: string }>;
}
const inspectFields = [
"\"image\":{{json .Image}}",
"\"hash\":{{json (index .Config.Labels \"com.docker.compose.config-hash\")}}",
"\"directory\":{{json (index .Config.Labels \"com.docker.compose.project.working_dir\")}}",
"\"oneOff\":{{json (index .Config.Labels \"com.docker.compose.oneoff\")}}",
];
const inspectFormat = `{${inspectFields.join(",")}}`;
export class StackAutoUpdate {
private schedule?: Cron;
private runInProgress = false;
private readonly shutdown = new AbortController();
constructor(private readonly server: DockgeServer) {}
/** Run daily on this host, including when no browser is connected. */
start() {
this.schedule = new Cron("0 4 * * *", {
timezone: "UTC",
protect: true,
}, () => this.run());
}
/** Stop scheduling and terminate commands during application shutdown. */
stop() {
this.schedule?.stop();
this.shutdown.abort();
}
/** Return an absent policy for stacks that cannot be scheduled. */
async getPolicy(stack: Stack): Promise<Policy | undefined> {
if (!stackName.test(stack.name) || stack.name === "dockge") {
return;
}
const dir = await fs.lstat(stack.path).catch(() => undefined);
if (!dir?.isDirectory() || !await Stack.composeFileExists(this.server.stacksDir, stack.name)) {
return;
}
try {
const file = path.join(stack.path, policyFile);
if (!(await fs.lstat(file)).isFile()) {
throw new Error("The policy is not a regular file");
}
const policy = JSON.parse(await fs.readFile(file, "utf8"));
const lastRun = policy?.lastRun;
const validPolicy: Policy = { enabled: policy?.enabled === true };
if (typeof lastRun?.at === "string" && Number.isFinite(Date.parse(lastRun.at)) && outcomes.includes(lastRun.result)) {
validPolicy.lastRun = {
at: lastRun.at,
result: lastRun.result,
};
}
return validPolicy;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
log.warn("auto-update", `Could not read policy for ${stack.name}`);
}
return { enabled: false };
}
}
/** Persist the administrator's explicit choice for this stack. */
async setEnabled(stack: Stack, enabled: boolean): Promise<Policy> {
const current = await this.getPolicy(stack);
if (!current) {
throw new ValidationError("Automatic updates are unavailable for this stack.");
}
const policy = {
...current,
enabled,
};
await this.writePolicy(stack, policy);
return policy;
}
/** Check each opted-in stack once per scheduled run. */
async run(): Promise<void> {
if (this.runInProgress || this.shutdown.signal.aborted) {
return;
}
this.runInProgress = true;
try {
const dirs = await fs.readdir(this.server.stacksDir, { withFileTypes: true });
for (const dir of dirs) {
if (this.shutdown.signal.aborted) {
break;
}
if (!dir.isDirectory() || !stackName.test(dir.name) || dir.name === "dockge") {
continue;
}
const stack = new Stack(this.server, dir.name);
if (!(await this.getPolicy(stack))?.enabled) {
continue;
}
try {
await Stack.withOperation(this.server, dir.name, async () => {
const policy = await this.getPolicy(stack);
if (!policy?.enabled) {
return;
}
let result: Outcome;
try {
result = await this.update(stack);
} catch (error) {
result = "failed";
log.warn("auto-update", `${stack.name}: ${String(error)}`);
}
const current = await this.getPolicy(stack);
if (!current?.enabled) {
return;
}
await this.writePolicy(stack, {
...current,
lastRun: {
at: new Date().toISOString(),
result,
},
});
log.info("auto-update", `${stack.name}: ${result}`);
});
} catch (error) {
log.warn("auto-update", `${stack.name}: ${String(error)}`);
}
}
} catch (error) {
log.warn("auto-update", String(error));
} finally {
this.runInProgress = false;
}
}
/** Replace the policy atomically without exposing a partially written file. */
private async writePolicy(stack: Stack, policy: Policy): Promise<void> {
const file = path.join(stack.path, policyFile);
const temp = `${file}.${randomUUID()}.tmp`;
try {
await fs.writeFile(temp, JSON.stringify(policy) + "\n", {
flag: "wx",
mode: 0o600,
});
await fs.rename(temp, file);
} finally {
await fs.rm(temp, { force: true });
}
}
/** Pull and recreate only running services whose image actually changed. */
private async update(stack: Stack): Promise<Outcome> {
const before = await this.getCandidates(stack);
if (before.size === 0) {
return "skipped";
}
await this.docker(stack, stack.getComposeOptions("pull", "--policy", "always", "--ignore-buildable", "--", ...before.keys()));
const after = await this.getCandidates(stack);
const changed = new Map<string, Candidate>();
let skipped = false;
for (const [ name, original ] of before) {
const current = after.get(name);
if (!current || original.hash !== current.hash || original.image !== current.image
|| original.containers.join() !== current.containers.join()) {
skipped = true;
continue;
}
const imageId = await this.docker(stack, [ "image", "inspect", "--format", "{{.Id}}", "--", current.image ]);
if (!/^sha256:[a-f0-9]{64}$/.test(imageId)) {
throw new Error("Docker image inspect returned an invalid image ID");
}
if (current.imageIds.some(id => id !== imageId)) {
changed.set(name, current);
}
}
if (!changed.size) {
return skipped ? "skipped" : "unchanged";
}
if (!(await this.getPolicy(stack))?.enabled) {
return "skipped";
}
const scale = Array.from(changed, ([ name, service ]) => [ "--scale", `${name}=${service.containers.length}` ]).flat();
await this.docker(stack, stack.getComposeOptions("up", "-d", "--no-deps", "--no-build", "--pull", "never",
"--wait", "--wait-timeout", "120", ...scale, "--", ...changed.keys()));
return "updated";
}
/** Restrict candidates to unchanged, running services owned by this stack directory. */
private async getCandidates(stack: Stack): Promise<Map<string, Candidate>> {
const result = new Map<string, Candidate>();
const ps = await this.docker(stack, stack.getComposeOptions("ps", "--all", "--orphans=false", "--format", "json"));
if (!ps) {
return result;
}
const containers: ContainerSummary[] = ps.startsWith("[") ? JSON.parse(ps) : ps.split(/\r?\n/).map(line => JSON.parse(line));
if (!containers.length || !containers.every(container => /^[a-f0-9]{12,64}$/.test(container.ID))) {
return result;
}
const localHostname = hostname();
if (/^[a-f0-9]{12,64}$/.test(localHostname) && containers.some(container => container.ID.startsWith(localHostname))) {
return result;
}
const configJson = await this.docker(stack, stack.getComposeOptions("config", "--format", "json"));
let config: ComposeConfig;
try {
config = JSON.parse(configJson);
} catch {
throw new Error("Docker Compose did not return valid configuration JSON");
}
if (config.name === "dockge" || Object.values(config.services).some(service => dockgeImage.test(service.image || ""))) {
return result;
}
const configHashes = await this.docker(stack, stack.getComposeOptions("config", "--hash", "*"));
const hashes = new Map(configHashes.split(/\r?\n/).map(line => {
const [ name, hash ] = line.trim().split(/\s+/);
return [ name, hash ];
}));
const info = await this.docker(stack, [ "container", "inspect", "--format", inspectFormat, "--", ...containers.map(container => container.ID) ]);
const details: ContainerDetails[] = info.split(/\r?\n/).map(line => JSON.parse(line));
if (details.length !== containers.length) {
throw new Error("Docker container inspect did not return all requested containers");
}
const services = new Map<string, Array<ContainerSummary & ContainerDetails>>();
containers.forEach((container, index) => {
if (details[index].oneOff?.toLowerCase() !== "false") {
return;
}
const entries = services.get(container.Service) ?? [];
entries.push({
...container,
...details[index],
});
services.set(container.Service, entries);
});
for (const [ name, entries ] of services) {
const service = config.services[name];
const hash = hashes.get(name);
if (!service?.image || service.build || service.platform || service.pull_policy === "never"
|| !hash || !/^[a-f0-9]{64}$/.test(hash)) {
continue;
}
const directory = path.resolve(stack.path);
if (!entries.every(container => container.State === "running" && container.hash === hash
&& container.directory && path.resolve(container.directory) === directory)) {
continue;
}
result.set(name, {
image: service.image,
hash,
containers: entries.map(container => container.ID).sort(),
imageIds: entries.map(container => container.image),
});
}
return result;
}
/** Run Docker without a shell and keep raw Compose configuration out of logs. */
private async docker(stack: Stack, args: string[]): Promise<string> {
try {
const { stdout } = await exec("docker", args, {
cwd: stack.path,
env: {
...process.env,
COMPOSE_REMOVE_ORPHANS: "false",
},
encoding: "utf8",
timeout: 15 * 60 * 1000,
maxBuffer: 16 * 1024 * 1024,
signal: this.shutdown.signal,
windowsHide: true,
});
return stdout.trim();
} catch (error) {
const code = (error as NodeJS.ErrnoException).code ?? "interrupted";
throw new Error(`Docker ${args[0]} command failed (${code})`);
}
}
}

View File

@ -1,109 +0,0 @@
import { randomUUID } from "node:crypto";
import { promises as fs } from "node:fs";
import path from "node:path";
const writesInProgress = new Set<string>();
interface StackFile {
path: string;
content: string;
mode: number;
}
interface PreparedFile {
target: string;
next: string;
backup?: string;
preserveBackup: boolean;
}
/** Replace the pair only after staging both files, and restore committed files on failure. */
export async function saveStackFiles(files: StackFile[], owner?: { uid: number; gid: number }, beforeCommit?: () => void): Promise<void> {
const prepared: PreparedFile[] = [];
const committed: PreparedFile[] = [];
const lockedPaths: string[] = [];
try {
for (const file of files) {
const link = await fs.lstat(file.path).catch((error: NodeJS.ErrnoException) => {
if (error.code !== "ENOENT") {
throw error;
}
return undefined;
});
const target = link?.isSymbolicLink() ? await fs.realpath(file.path) : file.path;
if (prepared.some(item => path.resolve(item.target) === path.resolve(target))) {
throw new Error("editorFileConflict");
}
const resolved = path.resolve(target);
const key = process.platform === "win32" ? resolved.toLowerCase() : resolved;
if (writesInProgress.has(key)) {
throw new Error("Another operation is already running, please try again later.");
}
writesInProgress.add(key);
lockedPaths.push(key);
const stat = link ? await fs.stat(target) : undefined;
if (stat && !stat.isFile()) {
throw new Error("editorFileNotRegular");
}
const item: PreparedFile = {
target,
next: target + ".dockge-" + randomUUID() + ".tmp",
preserveBackup: false,
};
prepared.push(item);
const mode = stat ? stat.mode & 0o777 : file.mode;
await fs.writeFile(item.next, file.content, {
flag: "wx",
mode,
});
if (stat) {
item.backup = target + ".dockge-" + randomUUID() + ".bak";
await fs.copyFile(target, item.backup);
await fs.chmod(item.backup, mode);
}
const fileOwner = owner ?? stat;
if (process.platform !== "win32" && fileOwner) {
await fs.chown(item.next, fileOwner.uid, fileOwner.gid);
if (item.backup && stat) {
await fs.chown(item.backup, stat.uid, stat.gid);
}
}
}
beforeCommit?.();
try {
for (const item of prepared) {
await fs.rename(item.next, item.target);
committed.push(item);
}
} catch (error) {
let recoveryFailed = false;
for (const item of committed.reverse()) {
try {
if (item.backup) {
await fs.rename(item.backup, item.target);
} else {
await fs.unlink(item.target);
}
} catch {
item.preserveBackup = true;
recoveryFailed = true;
}
}
if (recoveryFailed) {
throw new Error("editorSaveRecoveryFailed");
}
throw error;
}
} finally {
for (const item of prepared) {
await fs.rm(item.next, { force: true }).catch(() => {});
if (item.backup && !item.preserveBackup) {
await fs.rm(item.backup, { force: true }).catch(() => {});
}
}
for (const key of lockedPaths) {
writesInProgress.delete(key);
}
}
}

View File

@ -1,6 +1,5 @@
import { DockgeServer } from "./dockge-server"; import { DockgeServer } from "./dockge-server";
import fs, { promises as fsAsync } from "fs"; import fs, { promises as fsAsync } from "fs";
import { createHash } from "node:crypto";
import { log } from "./log"; import { log } from "./log";
import yaml from "yaml"; import yaml from "yaml";
import { DockgeSocket, fileExists, ValidationError } from "./util-server"; import { DockgeSocket, fileExists, ValidationError } from "./util-server";
@ -20,8 +19,6 @@ import {
import { InteractiveTerminal, Terminal } from "./terminal"; import { InteractiveTerminal, Terminal } from "./terminal";
import childProcessAsync from "promisify-child-process"; import childProcessAsync from "promisify-child-process";
import { Settings } from "./settings"; import { Settings } from "./settings";
import { analyzeEnv } from "../common/env-file";
import { saveStackFiles } from "./stack-files";
export class Stack { export class Stack {
@ -36,27 +33,6 @@ export class Stack {
protected combinedTerminal? : Terminal; protected combinedTerminal? : Terminal;
protected static managedStackList: Map<string, Stack> = new Map(); protected static managedStackList: Map<string, Stack> = new Map();
private static operations = new Set<string>();
/**
* Hold the stack lock across filesystem changes and all Compose steps.
* @param server Dockge instance that owns the stack
* @param name Stack directory name
* @param action Operation to run
* @returns The operation result
*/
static async withOperation<T>(server: DockgeServer, name: string, action: () => Promise<T>): Promise<T> {
const directory = path.resolve(server.stacksDir, name);
if (this.operations.has(directory)) {
throw new ValidationError("Another operation is already running, please try again later.");
}
this.operations.add(directory);
try {
return await action();
} finally {
this.operations.delete(directory);
}
}
constructor(server : DockgeServer, name : string, composeYAML? : string, composeENV? : string, skipFSOperations = false) { constructor(server : DockgeServer, name : string, composeYAML? : string, composeENV? : string, skipFSOperations = false) {
this.name = name; this.name = name;
@ -99,7 +75,6 @@ export class Stack {
composeYAML: this.composeYAML, composeYAML: this.composeYAML,
composeENV: this.composeENV, composeENV: this.composeENV,
primaryHostname, primaryHostname,
revision: this.revision,
}; };
} }
@ -136,10 +111,6 @@ export class Stack {
return this._status; return this._status;
} }
get revision(): string {
return createHash("sha256").update(JSON.stringify([ this._composeFileName, this.composeYAML, this.composeENV ])).digest("hex");
}
validate() { validate() {
// Check name, allows [a-z][0-9] _ - only // Check name, allows [a-z][0-9] _ - only
if (!this.name.match(/^[a-z0-9_-]+$/)) { if (!this.name.match(/^[a-z0-9_-]+$/)) {
@ -147,15 +118,15 @@ export class Stack {
} }
// Check YAML format // Check YAML format
const config = yaml.parse(this.composeYAML); yaml.parse(this.composeYAML);
if (config !== null && (typeof config !== "object" || Array.isArray(config))) {
throw new ValidationError("editorYamlMapping"); let lines = this.composeENV.split("\n");
}
if (config?.services && (typeof config.services !== "object" || Array.isArray(config.services))) { // Check if the .env is able to pass docker-compose
throw new ValidationError("editorServicesMapping"); // Prevent "setenv: The parameter is incorrect"
} // It only happens when there is one line and it doesn't contain "="
if (analyzeEnv(this.composeENV).some(issue => issue.severity === "error")) { if (lines.length === 1 && !lines[0].includes("=") && lines[0].length > 0) {
throw new ValidationError("editorInvalidEnv"); throw new ValidationError("Invalid .env format");
} }
} }
@ -203,32 +174,11 @@ export class Stack {
/** /**
* Save the stack to the disk * Save the stack to the disk
* @param isAdd * @param isAdd
* @param expectedRevision Version loaded by the editor, omitted by legacy clients
*/ */
async save(isAdd : boolean, expectedRevision?: string) { async save(isAdd : boolean) {
this.validate(); this.validate();
let dir = this.path; let dir = this.path;
let owner;
if (process.env.PUID && process.env.PGID) {
const uid = Number(process.env.PUID);
const gid = Number(process.env.PGID);
if (!Number.isSafeInteger(uid) || uid < 0 || !Number.isSafeInteger(gid) || gid < 0) {
throw new ValidationError("Invalid PUID or PGID");
}
owner = {
uid,
gid,
};
}
const checkRevision = () => {
if (!isAdd && expectedRevision !== undefined) {
const current = new Stack(this.server, this.name);
if (current.revision !== expectedRevision && current.revision !== this.revision) {
throw new ValidationError("editorConflict");
}
}
};
// Check if the name is used if isAdd // Check if the name is used if isAdd
if (isAdd) { if (isAdd) {
@ -242,40 +192,23 @@ export class Stack {
if (!await fileExists(dir)) { if (!await fileExists(dir)) {
throw new ValidationError("Stack not found"); throw new ValidationError("Stack not found");
} }
checkRevision();
} }
try { // Write or overwrite the compose.yaml
if (owner) { await fsAsync.writeFile(path.join(dir, this._composeFileName), this.composeYAML);
await fsAsync.lchown(dir, owner.uid, owner.gid);
} const envPath = path.join(dir, ".env");
await saveStackFiles([
{ // Write or overwrite the .env
path: path.join(dir, this._composeFileName), // If .env is not existing and the composeENV is empty, we don't need to write it
content: this.composeYAML, if (await fileExists(envPath) || this.composeENV.trim() !== "") {
mode: 0o644, await fsAsync.writeFile(envPath, this.composeENV);
},
{
path: path.join(dir, ".env"),
content: this.composeENV,
mode: 0o600,
},
], owner, checkRevision);
} catch (error) {
if (isAdd) {
await fsAsync.rmdir(dir).catch(() => {});
}
throw error;
} }
} }
async deploy(socket : DockgeSocket) : Promise<number> { async deploy(socket : DockgeSocket) : Promise<number> {
const terminalName = getComposeTerminalName(socket.endpoint, this.name); const terminalName = getComposeTerminalName(socket.endpoint, this.name);
let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", this.getComposeOptions("config", "--quiet"), this.path); let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", this.getComposeOptions("up", "-d", "--remove-orphans"), this.path);
if (exitCode !== 0) {
throw new ValidationError("editorComposeInvalid");
}
exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", this.getComposeOptions("up", "-d", "--remove-orphans"), this.path);
if (exitCode !== 0) { if (exitCode !== 0) {
throw new Error("Failed to deploy, please check the terminal output for more information."); throw new Error("Failed to deploy, please check the terminal output for more information.");
} }
@ -577,7 +510,7 @@ export class Stack {
} }
async getServiceStatusList() { async getServiceStatusList() {
let statusList = new Map<string, Array<object>>(); let statusList = new Map<string, { state: string, ports: string[] }>();
try { try {
let res = await childProcessAsync.spawn("docker", this.getComposeOptions("ps", "--format", "json"), { let res = await childProcessAsync.spawn("docker", this.getComposeOptions("ps", "--format", "json"), {
@ -591,23 +524,22 @@ export class Stack {
let lines = res.stdout?.toString().split("\n"); let lines = res.stdout?.toString().split("\n");
const addLine = (obj: { Service: string, State: string, Name: string, Health: string }) => {
if (!statusList.has(obj.Service)) {
statusList.set(obj.Service, []);
}
statusList.get(obj.Service)?.push({
status: obj.Health || obj.State,
name: obj.Name
});
};
for (let line of lines) { for (let line of lines) {
try { try {
let obj = JSON.parse(line); let obj = JSON.parse(line);
if (obj instanceof Array) { let ports = (obj.Ports as string).split(/,\s*/).filter((s) => {
obj.forEach(addLine); return s.indexOf("->") >= 0;
});
if (obj.Health === "") {
statusList.set(obj.Service, {
state: obj.State,
ports: ports
});
} else { } else {
addLine(obj); statusList.set(obj.Service, {
state: obj.Health,
ports: ports
});
} }
} catch (e) { } catch (e) {
} }
@ -618,35 +550,6 @@ export class Stack {
log.error("getServiceStatusList", e); log.error("getServiceStatusList", e);
return statusList; return statusList;
} }
}
async startService(socket: DockgeSocket, serviceName: string) {
const terminalName = getComposeTerminalName(socket.endpoint, this.name);
const exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "up", "-d", serviceName ], this.path);
if (exitCode !== 0) {
throw new Error(`Failed to start service ${serviceName}, please check logs for more information.`);
}
return exitCode;
}
async stopService(socket: DockgeSocket, serviceName: string): Promise<number> {
const terminalName = getComposeTerminalName(socket.endpoint, this.name);
const exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "stop", serviceName ], this.path);
if (exitCode !== 0) {
throw new Error(`Failed to stop service ${serviceName}, please check logs for more information.`);
}
return exitCode;
}
async restartService(socket: DockgeSocket, serviceName: string): Promise<number> {
const terminalName = getComposeTerminalName(socket.endpoint, this.name);
const exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", [ "compose", "restart", serviceName ], this.path);
if (exitCode !== 0) {
throw new Error(`Failed to restart service ${serviceName}, please check logs for more information.`);
}
return exitCode;
} }
} }

View File

@ -7,12 +7,14 @@ import { R } from "redbean-node";
import { verifyPassword } from "./password-hash"; import { verifyPassword } from "./password-hash";
import fs from "fs"; import fs from "fs";
import { AgentManager } from "./agent-manager"; import { AgentManager } from "./agent-manager";
import type { AuthSession } from "./auth-session";
export interface JWTDecoded {
username : string;
h? : string;
}
export interface DockgeSocket extends Socket { export interface DockgeSocket extends Socket {
userID: number; userID: number;
authBypassed?: boolean;
authSession?: AuthSession;
consoleTerminal? : Terminal; consoleTerminal? : Terminal;
instanceManager : AgentManager; instanceManager : AgentManager;
endpoint : string; endpoint : string;

View File

@ -1,71 +0,0 @@
export interface EnvIssue {
from: number;
to: number;
severity: "error" | "warning";
message: string;
}
/** Find malformed quoted values and repeated keys without reporting secret values. */
export function analyzeEnv(source: string): EnvIssue[] {
const issues: EnvIssue[] = [];
const keys = new Set<string>();
let quote = "";
let quoteStart = 0;
let offset = 0;
for (const line of source.split("\n")) {
let index = 0;
if (!quote) {
const assignment = /^(?:\uFEFF)?\s*(?:export\s+)?([^\s=:#]+)\s*(?:=|:\s+)/.exec(line);
if (assignment && !line.trimStart().startsWith("#")) {
if (keys.has(assignment[1])) {
issues.push({
from: offset,
to: offset + line.length,
severity: "warning",
message: "editorEnvDuplicate",
});
}
keys.add(assignment[1]);
index = assignment[0].length;
while (/\s/.test(line[index] || "") && index < line.length) {
index++;
}
if (line[index] === "'" || line[index] === "\"") {
quote = line[index];
quoteStart = offset + index;
index++;
}
}
}
if (quote) {
for (; index < line.length; index++) {
if (line[index] === "\\") {
index++;
} else if (line[index] === quote) {
quote = "";
break;
}
}
}
offset += line.length + 1;
}
if (quote) {
issues.push({
from: quoteStart,
to: Math.min(source.length, quoteStart + 1),
severity: "error",
message: "editorEnvUnclosedQuote",
});
}
const nul = source.indexOf("\0");
if (nul >= 0) {
issues.push({
from: nul,
to: nul + 1,
severity: "error",
message: "editorEnvNull",
});
}
return issues;
}

View File

@ -16,30 +16,12 @@ RUN npm ci --omit=dev
# ⭐ Main Image # ⭐ Main Image
############################################ ############################################
FROM louislam/dockge:base AS release FROM louislam/dockge:base AS release
ARG TARGETARCH
WORKDIR /app WORKDIR /app
COPY --chown=node:node --from=build_healthcheck /app/extra/healthcheck /app/extra/healthcheck COPY --chown=node:node --from=build_healthcheck /app/extra/healthcheck /app/extra/healthcheck
COPY --from=build /app/node_modules /app/node_modules COPY --from=build /app/node_modules /app/node_modules
COPY --chown=node:node . . COPY --chown=node:node . .
RUN mkdir ./data RUN mkdir ./data
# Grype is available upstream for the amd64 and arm64 images.
RUN set -eu; \
case "$TARGETARCH" in \
amd64) checksum=e9da18cc1429e786722e32161288103600efffd8e483c90761f90485bd1bec85 ;; \
arm64) checksum=b7815598d48da78bfd16f5b98ef28e1bb09c03d34fc8c3e350f99b6ccb3c7cba ;; \
*) echo "Install Grype separately to enable image scans on $TARGETARCH"; exit 0 ;; \
esac; \
temp_dir="$(mktemp -d)"; \
trap 'rm -rf "$temp_dir"' EXIT; \
curl --fail --location --retry 3 \
"https://github.com/anchore/grype/releases/download/v0.121.3/grype_0.121.3_linux_${TARGETARCH}.tar.gz" \
--output "$temp_dir/grype.tar.gz"; \
echo "$checksum $temp_dir/grype.tar.gz" | sha256sum --check --status; \
tar -xzf "$temp_dir/grype.tar.gz" -C "$temp_dir" grype LICENSE; \
install -m 0755 "$temp_dir/grype" /usr/local/bin/grype; \
install -D -m 0644 "$temp_dir/LICENSE" /usr/share/doc/grype/LICENSE
# It is just for safe, as by default, it is disabled in the latest Node.js now. # It is just for safe, as by default, it is disabled in the latest Node.js now.
# Read more: # Read more:

View File

@ -11,32 +11,23 @@ declare module 'vue' {
Appearance: typeof import('./src/components/settings/Appearance.vue')['default'] Appearance: typeof import('./src/components/settings/Appearance.vue')['default']
ArrayInput: typeof import('./src/components/ArrayInput.vue')['default'] ArrayInput: typeof import('./src/components/ArrayInput.vue')['default']
ArraySelect: typeof import('./src/components/ArraySelect.vue')['default'] ArraySelect: typeof import('./src/components/ArraySelect.vue')['default']
BButton: typeof import('bootstrap-vue-next')['BButton']
BDropdown: typeof import('bootstrap-vue-next')['BDropdown'] BDropdown: typeof import('bootstrap-vue-next')['BDropdown']
BDropdownItem: typeof import('bootstrap-vue-next')['BDropdownItem'] BDropdownItem: typeof import('bootstrap-vue-next')['BDropdownItem']
BFormGroup: typeof import('bootstrap-vue-next')['BFormGroup']
BFormInput: typeof import('bootstrap-vue-next')['BFormInput']
BModal: typeof import('bootstrap-vue-next')['BModal'] BModal: typeof import('bootstrap-vue-next')['BModal']
Confirm: typeof import('./src/components/Confirm.vue')['default'] Confirm: typeof import('./src/components/Confirm.vue')['default']
Container: typeof import('./src/components/Container.vue')['default'] Container: typeof import('./src/components/Container.vue')['default']
DockerStat: typeof import('./src/components/DockerStat.vue')['default']
General: typeof import('./src/components/settings/General.vue')['default'] General: typeof import('./src/components/settings/General.vue')['default']
GlobalEnv: typeof import('./src/components/settings/GlobalEnv.vue')['default'] GlobalEnv: typeof import('./src/components/settings/GlobalEnv.vue')['default']
HiddenInput: typeof import('./src/components/HiddenInput.vue')['default'] HiddenInput: typeof import('./src/components/HiddenInput.vue')['default']
ImageVulnerabilities: typeof import('./src/components/ImageVulnerabilities.vue')['default']
Login: typeof import('./src/components/Login.vue')['default'] Login: typeof import('./src/components/Login.vue')['default']
NetworkInput: typeof import('./src/components/NetworkInput.vue')['default'] NetworkInput: typeof import('./src/components/NetworkInput.vue')['default']
RouterLink: typeof import('vue-router')['RouterLink'] RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView'] RouterView: typeof import('vue-router')['RouterView']
Security: typeof import('./src/components/settings/Security.vue')['default'] Security: typeof import('./src/components/settings/Security.vue')['default']
StackConfigEditor: typeof import('./src/components/StackConfigEditor.vue')['default']
StackList: typeof import('./src/components/StackList.vue')['default'] StackList: typeof import('./src/components/StackList.vue')['default']
StackListItem: typeof import('./src/components/StackListItem.vue')['default'] StackListItem: typeof import('./src/components/StackListItem.vue')['default']
Terminal: typeof import('./src/components/Terminal.vue')['default'] Terminal: typeof import('./src/components/Terminal.vue')['default']
TwoFADialog: typeof import('./src/components/TwoFADialog.vue')['default'] TwoFADialog: typeof import('./src/components/TwoFADialog.vue')['default']
Uptime: typeof import('./src/components/Uptime.vue')['default'] Uptime: typeof import('./src/components/Uptime.vue')['default']
} }
export interface ComponentCustomProperties {
vBModal: typeof import('bootstrap-vue-next')['vBModal']
}
} }

View File

@ -1,7 +1,7 @@
<template> <template>
<div class="shadow-box big-padding mb-3 container"> <div class="shadow-box big-padding mb-3 container">
<div class="row"> <div class="row">
<div class="col-5"> <div class="col-7">
<h4>{{ name }}</h4> <h4>{{ name }}</h4>
<div class="image mb-2"> <div class="image mb-2">
<span class="me-1">{{ imageName }}:</span><span class="tag">{{ imageTag }}</span> <span class="me-1">{{ imageName }}:</span><span class="tag">{{ imageTag }}</span>
@ -14,41 +14,12 @@
</a> </a>
</div> </div>
</div> </div>
<div class="col-7"> <div class="col-5">
<div class="function"> <div class="function">
<div class="btn-group me-2" role="group"> <router-link v-if="!isEditMode" class="btn btn-normal" :to="terminalRouteLink" disabled="">
<router-link v-if="!isEditMode && (status === 'running' || status === 'healthy')" class="btn btn-normal" :to="terminalRouteLink" disabled="">
<font-awesome-icon icon="terminal" /> <font-awesome-icon icon="terminal" />
Bash Bash
</router-link> </router-link>
<button
v-if="serviceCount > 1 && !isEditMode && status !== 'running' && status !== 'healthy'"
class="btn btn-primary"
:disabled="processing"
@click="startService"
>
<font-awesome-icon icon="play" class="me-1" />
{{ $t("startStack") }}
</button>
<button
v-if="serviceCount > 1 && !isEditMode && (status === 'running' || status === 'healthy' || status === 'unhealthy')"
class="btn btn-normal"
:disabled="processing"
@click="restartService"
>
<font-awesome-icon icon="rotate" class="me-1" />
{{ $t("restartStack") }}
</button>
<button
v-if="serviceCount > 1 && !isEditMode && (status === 'running' || status === 'healthy' || status === 'unhealthy')"
class="btn btn-normal"
:disabled="processing"
@click="stopService"
>
<font-awesome-icon icon="stop" class="me-1" />
{{ $t("stopStack") }}
</button>
</div>
</div> </div>
</div> </div>
</div> </div>
@ -64,32 +35,6 @@
{{ $t("deleteContainer") }} {{ $t("deleteContainer") }}
</button> </button>
</div> </div>
<div v-else-if="statsInstances.length > 0" class="mt-2">
<div class="d-flex align-items-center gap-3">
<template v-if="!expandedStats">
<div class="stats">
{{ $t('CPU') }}: {{ statsInstances[0].CPUPerc }}
</div>
<div class="stats">
{{ $t('memoryAbbreviated') }}: {{ statsInstances[0].MemUsage }}
</div>
</template>
<div class="d-flex flex-grow-1 justify-content-end">
<button class="btn btn-sm btn-normal" @click="expandedStats = !expandedStats">
<font-awesome-icon :icon="expandedStats ? 'chevron-up' : 'chevron-down'" />
</button>
</div>
</div>
<transition name="slide-fade" appear>
<div v-if="expandedStats" class="d-flex flex-column gap-3 mt-2">
<DockerStat
v-for="stat in statsInstances"
:key="stat.Name"
:stat="stat"
/>
</div>
</transition>
</div>
<transition name="slide-fade" appear> <transition name="slide-fade" appear>
<div v-if="isEditMode && showConfig" class="config mt-3"> <div v-if="isEditMode && showConfig" class="config mt-3">
@ -193,12 +138,10 @@
import { defineComponent } from "vue"; import { defineComponent } from "vue";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import { parseDockerPort } from "../../../common/util-common"; import { parseDockerPort } from "../../../common/util-common";
import DockerStat from "./DockerStat.vue";
export default defineComponent({ export default defineComponent({
components: { components: {
FontAwesomeIcon, FontAwesomeIcon,
DockerStat
}, },
props: { props: {
name: { name: {
@ -213,24 +156,20 @@ export default defineComponent({
type: Boolean, type: Boolean,
default: false, default: false,
}, },
serviceStatus: { status: {
type: Object, type: String,
default: null, default: "N/A",
}, },
dockerStats: { ports: {
type: Object, type: Array,
default: null default: null
} }
}, },
emits: [ emits: [
"start-service",
"stop-service",
"restart-service"
], ],
data() { data() {
return { return {
showConfig: false, showConfig: false,
expandedStats: false,
}; };
}, },
computed: { computed: {
@ -295,10 +234,6 @@ export default defineComponent({
return this.jsonObject.services[this.name]; return this.jsonObject.services[this.name];
}, },
serviceCount() {
return Object.keys(this.jsonObject.services).length;
},
jsonObject() { jsonObject() {
return this.$parent.$parent.jsonConfig; return this.$parent.$parent.jsonConfig;
}, },
@ -335,22 +270,6 @@ export default defineComponent({
return ""; return "";
} }
}, },
statsInstances() {
if (!this.serviceStatus) {
return [];
}
return this.serviceStatus
.map(s => this.dockerStats[s.name])
.filter(s => !!s)
.sort((a, b) => a.Name.localeCompare(b.Name));
},
status() {
if (!this.serviceStatus) {
return "N/A";
}
return this.serviceStatus[0].status;
}
}, },
mounted() { mounted() {
if (this.first) { if (this.first) {
@ -369,16 +288,6 @@ export default defineComponent({
remove() { remove() {
delete this.jsonObject.services[this.name]; delete this.jsonObject.services[this.name];
}, },
startService() {
this.$emit("start-service", this.name);
},
stopService() {
this.$emit("stop-service", this.name);
},
restartService() {
this.$emit("restart-service", this.name);
}
} }
}); });
</script> </script>
@ -403,10 +312,5 @@ export default defineComponent({
align-items: center; align-items: center;
justify-content: end; justify-content: end;
} }
.stats {
font-size: 0.8rem;
color: #6c757d;
}
} }
</style> </style>

View File

@ -1,94 +0,0 @@
<template>
<div class="stats-container">
<div class="stats-title">
{{ stat.Name }}
</div>
<div class="d-flex justify-content-between stats gap-2 mt-1">
<div class="stat">
<div class="stat-label">
{{ $t('CPU') }}
</div>
<div>
{{ stat.CPUPerc }}
</div>
</div>
<div class="stat">
<div class="stat-label">
{{ $t('memory') }}
</div>
<div>
{{ stat.MemUsage }} ({{ stat.MemPerc }})
</div>
</div>
<div class="stat">
<div class="stat-label">
{{ $t('networkIO') }}
</div>
<div>
{{ stat.NetIO }}
</div>
</div>
<div class="stat">
<div class="stat-label">
{{ $t('blockIO') }}
</div>
<div>
{{ stat.BlockIO }}
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
stat: {
type: Object,
required: true
}
},
};
</script>
<style lang="scss" scoped>
.stats-container {
container-type: inline-size;
.stats {
container-type: inline-size;
.stat {
display: flex;
flex-direction: column;
gap: 4px;
}
@container (width < 420px) {
flex-direction: column;
.stat {
flex-direction: row;
}
.stat-label::after {
content: ':'
}
}
}
}
.stats {
font-size: 0.8rem;
color: #6c757d;
}
.stat-label {
font-weight: bold;
}
.stats-title {
font-size: 0.9rem;
color: var(--bs-heading-color);
}
</style>

View File

@ -1,370 +0,0 @@
<template>
<section class="shadow-box image-security mb-3" aria-labelledby="image-security-heading">
<div class="image-security-header">
<div>
<h2 id="image-security-heading" class="h5 mb-1">{{ $t("imageScanTitle") }}</h2>
<p class="small mb-0">{{ $t("imageScanDescription") }}</p>
</div>
<div class="image-security-actions">
<button type="button" class="btn btn-normal" :disabled="requestPending" @click="refreshReport">
{{ $t("imageScanRefresh") }}
</button>
<button type="button" class="btn btn-primary" :disabled="requestPending || running" @click="startScan">
{{ $t("imageScanStart") }}
</button>
</div>
</div>
<p v-if="error" class="alert alert-danger mt-3 mb-0" role="alert">{{ $t(error) }}</p>
<p v-if="running" class="mt-3 mb-0" role="status">
{{ $t("imageScanProgress", { completed: completedImages, total: report.images.length }) }}
</p>
<p v-else-if="report?.status === 'failed'" class="alert alert-warning mt-3 mb-0" role="status">
{{ $t(report.error) }}
</p>
<p v-else-if="report && report.images.length === 0" class="mt-3 mb-0">{{ $t("imageScanNoImages") }}</p>
<p v-else-if="!report && !requestPending" class="mt-3 mb-0">{{ $t("imageScanNotRun") }}</p>
<div v-if="report?.status === 'complete' && report.images.length" class="mt-3">
<div class="image-security-filters">
<label class="image-security-field">
<span>{{ $t("imageScanImage") }}</span>
<select v-model="selectedImage" class="form-select" :aria-label="$t('imageScanImage')" @change="loadFindings(0)">
<option v-for="image in report.images" :key="image.id" :value="image.id">
{{ image.references.join(", ") || image.id }} · {{ image.services.join(", ") }} · {{ $t("imageScanStatus." + image.status) }}
</option>
</select>
</label>
<label v-if="selected?.status === 'scanned'" class="image-security-field">
<span>{{ $t("imageScanSeverityLabel") }}</span>
<select v-model="severity" class="form-select" :aria-label="$t('imageScanSeverityLabel')" @change="loadFindings(0)">
<option value="">{{ $t("imageScanAllSeverities") }}</option>
<option v-for="level in severities" :key="level" :value="level">{{ $t("imageScanSeverity." + level) }}</option>
</select>
</label>
</div>
<template v-if="selected">
<p class="image-security-id small mt-2 mb-2">{{ selected.id }}</p>
<p v-if="selected.databaseBuiltAt" class="small mb-2">
{{ $t("imageScanDatabase", { time: new Date(selected.databaseBuiltAt).toLocaleString($i18n.locale) }) }}
<span v-if="selected.scannerVersion"> · Grype {{ selected.scannerVersion }}</span>
</p>
<p v-if="selected.error" class="alert alert-warning" role="status">{{ $t(selected.error) }}</p>
<template v-if="selected.status === 'scanned'">
<div class="image-security-counts" role="group" :aria-label="$t('imageScanCounts')">
<span v-for="level in severities" :key="level" class="image-security-severity" :data-severity="level">
{{ $t("imageScanSeverity." + level) }} {{ selected.counts[level] }}
</span>
</div>
<p v-if="selected.truncated" class="small mt-2 mb-0">{{ $t("imageScanTruncated") }}</p>
<p v-if="findingsPending" class="mt-3 mb-0" role="status">{{ $t("imageScanLoading") }}</p>
<p v-else-if="!rows.length && !error" class="mt-3 mb-0">{{ $t("imageScanNoFindings") }}</p>
<div v-else-if="rows.length" class="table-responsive mt-3">
<table class="table image-security-table">
<caption class="visually-hidden">{{ $t("imageScanFindings") }}</caption>
<thead>
<tr>
<th scope="col">{{ $t("imageScanSeverityLabel") }}</th>
<th scope="col">{{ $t("imageScanAdvisory") }}</th>
<th scope="col">{{ $t("imageScanPackage") }}</th>
<th scope="col">{{ $t("imageScanInstalled") }}</th>
<th scope="col">{{ $t("imageScanFixed") }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(finding, index) in rows" :key="index">
<td><span class="image-security-severity" :data-severity="finding.severity">{{ $t("imageScanSeverity." + finding.severity) }}</span></td>
<td>
<a v-if="advisoryURL(finding.id)" :href="advisoryURL(finding.id)" target="_blank" rel="noopener noreferrer">{{ finding.id }}</a>
<span v-else>{{ finding.id }}</span>
</td>
<td>{{ finding.packageName }}<span class="d-block small">{{ finding.packageType }} · {{ finding.namespace }}</span></td>
<td>{{ finding.installedVersion }}</td>
<td>{{ finding.fixedVersions.join(", ") || $t("imageScanFixUnknown") }}</td>
</tr>
</tbody>
</table>
</div>
<div v-if="total > pageSize" class="image-security-pagination mt-2">
<button type="button" class="btn btn-normal" :disabled="findingsPending || offset === 0" @click="loadFindings(offset - pageSize)">{{ $t("imageScanPrevious") }}</button>
<span class="small" role="status">{{ $t("imageScanPage", { first: offset + 1, last: Math.min(offset + pageSize, total), total }) }}</span>
<button type="button" class="btn btn-normal" :disabled="findingsPending || offset + pageSize >= total" @click="loadFindings(offset + pageSize)">{{ $t("imageScanNext") }}</button>
</div>
</template>
</template>
</div>
<p v-if="report?.finishedAt" class="small mt-3 mb-0">{{ $t("imageScanTimestamp", { time: new Date(report.finishedAt).toLocaleString($i18n.locale) }) }}</p>
<p class="small mt-2 mb-0">{{ $t("imageScanRetention") }}</p>
</section>
</template>
<script>
const severities = [ "critical", "high", "medium", "low", "negligible", "unknown" ];
export default {
props: {
stackName: {
type: String,
required: true,
},
endpoint: {
type: String,
required: true,
},
},
data() {
return {
report: null,
selectedImage: "",
severity: "",
rows: [],
offset: 0,
total: 0,
pageSize: 25,
error: "",
requestPending: false,
findingsPending: false,
severities,
pollTimer: null,
disposed: false,
findingsRequest: 0,
};
},
computed: {
running() {
return this.report?.status === "running";
},
completedImages() {
return this.report?.images.filter(image => image.status !== "pending").length ?? 0;
},
selected() {
return this.report?.images.find(image => image.id === this.selectedImage);
},
},
mounted() {
this.refreshReport();
},
beforeUnmount() {
this.disposed = true;
this.findingsRequest++;
clearTimeout(this.pollTimer);
},
methods: {
/**
* Send a bounded request to the host that owns this stack.
* @param {string} event Agent API event
* @param {...unknown} args Event parameters
* @returns {Promise<object>} Successful response
*/
async request(event, ...args) {
let res;
try {
res = await this.$root.getSocket().timeout(15000).emitWithAck("agent", this.endpoint, event, this.stackName, ...args);
} catch {
throw new Error("imageScanRequestFailed");
}
if (!res.ok) {
throw new Error(res.msg || "imageScanRequestFailed");
}
return res;
},
/** Load current progress, including a scan started from another browser. */
async refreshReport() {
await this.loadReport("getStackImageScan");
},
/** Start an on-demand scan on the selected host. */
async startScan() {
this.findingsRequest++;
this.findingsPending = false;
this.selectedImage = "";
this.rows = [];
await this.loadReport("startStackImageScan");
},
/**
* Poll only while a scan is active and stop on connection errors.
* @param {string} event Start or status event
* @returns {Promise<void>}
*/
async loadReport(event) {
if (this.requestPending || this.disposed) {
return;
}
clearTimeout(this.pollTimer);
this.requestPending = true;
this.error = "";
try {
const res = await this.request(event);
if (this.disposed) {
return;
}
this.report = res.report;
if (this.running) {
this.pollTimer = setTimeout(() => this.refreshReport(), 2000);
} else {
if (!this.selected || this.selected.status !== "scanned") {
this.selectedImage = this.report?.images.find(image => image.status === "scanned")?.id || this.report?.images[0]?.id || "";
}
await this.loadFindings(0);
}
} catch (error) {
if (!this.disposed) {
this.error = error.message || "imageScanRequestFailed";
}
} finally {
this.requestPending = false;
}
},
/**
* Fetch one page and discard responses superseded by a filter change.
* @param {number} offset Position in the filtered result
* @returns {Promise<void>}
*/
async loadFindings(offset) {
const request = ++this.findingsRequest;
this.rows = [];
this.total = 0;
this.offset = offset;
this.findingsPending = false;
if (this.selected?.status !== "scanned") {
return;
}
this.findingsPending = true;
this.error = "";
try {
const res = await this.request("getStackImageFindings", this.report.id, this.selectedImage, this.severity, offset);
if (!this.disposed && request === this.findingsRequest) {
this.rows = res.rows;
this.total = res.total;
this.pageSize = res.pageSize;
}
} catch (error) {
if (!this.disposed && request === this.findingsRequest) {
this.error = error.message || "imageScanRequestFailed";
}
} finally {
if (request === this.findingsRequest) {
this.findingsPending = false;
}
}
},
/**
* Link only known advisory identifier formats to their official reference pages.
* @param {string} id Vulnerability identifier
* @returns {string} Advisory URL, or an empty string
*/
advisoryURL(id) {
if (/^CVE-\d{4}-\d{4,}$/.test(id)) {
return `https://nvd.nist.gov/vuln/detail/${id}`;
}
if (/^GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}$/i.test(id)) {
return `https://github.com/advisories/${id}`;
}
return "";
},
},
};
</script>
<style scoped lang="scss">
.image-security {
min-width: 0;
}
.image-security-header,
.image-security-actions,
.image-security-counts,
.image-security-pagination {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.5rem;
}
.image-security-header {
justify-content: space-between;
gap: 1rem;
}
.image-security-filters {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(10rem, auto);
gap: 0.75rem;
}
.image-security-field {
display: grid;
gap: 0.25rem;
min-width: 0;
font-size: 0.875rem;
}
.image-security-id,
.image-security-table td {
overflow-wrap: anywhere;
}
.image-security-table {
min-width: 40rem;
font-size: 0.875rem;
}
.image-security-severity {
display: inline-flex;
align-items: center;
padding: 0.125rem 0.5rem;
border: 1px solid currentColor;
border-radius: 1rem;
color: #536270;
font-size: 0.75rem;
white-space: nowrap;
&[data-severity="critical"] {
color: #9d174d;
}
&[data-severity="high"] {
color: #ad2929;
}
&[data-severity="medium"] {
color: #8a490b;
}
&[data-severity="low"] {
color: #1d5a97;
}
}
.dark .image-security-severity {
color: #b1bdca;
&[data-severity="critical"] {
color: #ffa3ce;
}
&[data-severity="high"] {
color: #ffaaaa;
}
&[data-severity="medium"] {
color: #ffce8c;
}
&[data-severity="low"] {
color: #9ac8ff;
}
}
@media (max-width: 600px) {
.image-security-filters {
grid-template-columns: minmax(0, 1fr);
}
}
</style>

View File

@ -51,8 +51,6 @@ export default {
externalList: {}, externalList: {},
selectedExternalList: {}, selectedExternalList: {},
externalNetworkList: [], externalNetworkList: [],
loadingNetworkList: false,
applyingNetworks: false,
}; };
}, },
computed: { computed: {
@ -64,6 +62,10 @@ export default {
return this.$parent.$parent.stack; return this.$parent.$parent.stack;
}, },
editorFocus() {
return this.$parent.$parent.editorFocus;
},
endpoint() { endpoint() {
return this.$parent.$parent.endpoint; return this.$parent.$parent.endpoint;
}, },
@ -71,19 +73,16 @@ export default {
watch: { watch: {
"jsonConfig.networks": { "jsonConfig.networks": {
handler() { handler() {
if (!this.applyingNetworks) { if (this.editorFocus) {
console.debug("jsonConfig.networks changed");
this.loadNetworkList(); this.loadNetworkList();
} }
}, },
deep: true, deep: true,
flush: "sync",
}, },
"selectedExternalList": { "selectedExternalList": {
handler() { handler() {
if (this.loadingNetworkList) {
return;
}
for (const networkName in this.selectedExternalList) { for (const networkName in this.selectedExternalList) {
const enable = this.selectedExternalList[networkName]; const enable = this.selectedExternalList[networkName];
@ -99,17 +98,13 @@ export default {
this.applyToYAML(); this.applyToYAML();
}, },
deep: true, deep: true,
flush: "sync",
}, },
"networkList": { "networkList": {
handler() { handler() {
if (!this.loadingNetworkList) {
this.applyToYAML(); this.applyToYAML();
}
}, },
deep: true, deep: true,
flush: "sync",
} }
}, },
@ -119,7 +114,6 @@ export default {
}, },
methods: { methods: {
loadNetworkList() { loadNetworkList() {
this.loadingNetworkList = true;
this.networkList = []; this.networkList = [];
this.externalList = {}; this.externalList = {};
@ -141,7 +135,6 @@ export default {
for (const networkName in this.externalList) { for (const networkName in this.externalList) {
this.selectedExternalList[networkName] = true; this.selectedExternalList[networkName] = true;
} }
this.loadingNetworkList = false;
}, },
loadExternalNetworkList() { loadExternalNetworkList() {
@ -174,28 +167,27 @@ export default {
remove(index) { remove(index) {
this.networkList.splice(index, 1); this.networkList.splice(index, 1);
this.applyToYAML();
}, },
applyToYAML() { applyToYAML() {
if (this.loadingNetworkList) { if (this.editorFocus) {
return; return;
} }
const networks = {}; this.jsonConfig.networks = {};
// Internal networks // Internal networks
for (const networkRow of this.networkList) { for (const networkRow of this.networkList) {
networks[networkRow.key] = networkRow.value; this.jsonConfig.networks[networkRow.key] = networkRow.value;
} }
// External networks // External networks
for (const networkName in this.externalList) { for (const networkName in this.externalList) {
networks[networkName] = this.externalList[networkName]; this.jsonConfig.networks[networkName] = this.externalList[networkName];
} }
this.applyingNetworks = true; console.debug("applyToYAML", this.jsonConfig.networks);
this.jsonConfig.networks = networks;
this.applyingNetworks = false;
} }
}, },

View File

@ -1,495 +0,0 @@
<template>
<section ref="container" class="stack-config-editor" :aria-label="$t('editorTitle')">
<TabsRoot v-model="activeFile" class="config-tabs" :unmount-on-exit="false">
<div class="config-toolbar">
<TabList class="config-tab-list" :aria-label="$t('editorFiles')">
<TabTrigger value="yaml" class="config-tab">
{{ fileName }}
<span v-if="yamlErrorCount" class="config-error-count">{{ yamlErrorCount }}</span>
</TabTrigger>
<TabTrigger value="env" class="config-tab">
.env
<span v-if="envErrorCount" class="config-error-count">{{ envErrorCount }}</span>
</TabTrigger>
</TabList>
<div class="config-tools">
<button type="button" class="config-tool" @click="find">{{ $t("editorFind") }}</button>
<button v-if="editable && activeFile === 'yaml'" type="button" class="config-tool" :disabled="disabled || yamlErrorCount > 0" @click="formatYAML">{{ $t("editorFormat") }}</button>
<button type="button" class="config-tool" :aria-pressed="wrap" @click="wrap = !wrap">{{ $t("editorWrap") }}</button>
<button v-if="fullscreenAvailable" type="button" class="config-tool" :aria-pressed="fullscreen" @click="toggleFullscreen">{{ $t(fullscreen ? "editorExitFullscreen" : "editorFullscreen") }}</button>
</div>
</div>
<TabContent value="yaml" class="config-tab-content">
<CodeMirror
ref="yamlEditor" v-model="yamlModel" basic
:readonly="!editable || disabled" :wrap="wrap" :dark="$root.isDark"
:extensions="yamlExtensions" :keymap="saveKeymap" :linter="lintYAML"
:linter-config="{ delay: 200 }" gutter indent-unit=" "
@ready="labelEditor('yaml')" @update="updateCursor($event, 'yaml')"
/>
</TabContent>
<TabContent value="env" class="config-tab-content">
<CodeMirror
ref="envEditor" v-model="envModel" basic
:readonly="!editable || disabled" :wrap="wrap" :dark="$root.isDark"
:extensions="envExtensions" :keymap="saveKeymap" :linter="lintEnv"
:linter-config="{ delay: 200 }" gutter
@ready="labelEditor('env')" @update="updateCursor($event, 'env')"
/>
</TabContent>
</TabsRoot>
<div class="config-status" role="status">
<span>{{ $t(editable ? (dirty ? "editorUnsaved" : "editorSaved") : "editorReadOnly") }}</span>
<span>{{ $t("editorCursor", { line: cursor.line, column: cursor.column }) }}</span>
<span v-if="editable">{{ $t("editorSaveShortcut") }}</span>
</div>
<ul v-if="diagnostics.length" class="config-diagnostics" :aria-label="$t('editorDiagnostics')">
<li v-for="(issue, index) in diagnostics" :key="index" :class="'config-' + issue.severity">
<button type="button" @click="jumpTo(issue)">
{{ issue.file === "yaml" ? fileName : ".env" }} · {{ $t("editorLine", { line: issue.line }) }} · {{ issue.message }}
</button>
</li>
</ul>
</section>
</template>
<script>
import { TabContent, TabList, TabsRoot, TabTrigger } from "@ark-ui/vue/tabs";
import CodeMirror from "vue-codemirror6";
import { yaml as yamlLanguage } from "@codemirror/lang-yaml";
import { StreamLanguage } from "@codemirror/language";
import { indentWithTab } from "@codemirror/commands";
import { openSearchPanel } from "@codemirror/search";
import { dracula } from "thememirror";
import { parseDocument } from "yaml";
import { nextTick } from "vue";
import { analyzeEnv } from "../../../common/env-file";
const envLanguage = StreamLanguage.define({
startState() {
return { quote: "",
phase: "key",
valueStart: false };
},
token(stream, state) {
if (stream.sol() && !state.quote) {
state.phase = "key";
state.valueStart = false;
}
if (state.quote) {
while (!stream.eol()) {
const char = stream.next();
if (char === "\\") {
stream.next();
} else if (char === state.quote) {
state.quote = "";
break;
}
}
return "string";
}
if (stream.eatSpace()) {
return null;
}
if (stream.peek() === "#" && (stream.pos === 0 || /\s/.test(stream.string[stream.pos - 1]))) {
stream.skipToEnd();
return "comment";
}
if (state.phase === "key" && stream.match(/(?:export\s+)?[^\s=:#]+\s*(?==|:\s)/)) {
state.phase = "separator";
return "propertyName";
}
if (state.phase === "separator" && stream.match(/=|:\s+/)) {
state.phase = "value";
state.valueStart = true;
return "operator";
}
if (state.valueStart && (stream.peek() === "\"" || stream.peek() === "'")) {
state.valueStart = false;
state.quote = stream.next();
return "string";
}
state.valueStart = false;
if (stream.match(/\$\{[^}]*\}|\$[A-Za-z_][A-Za-z0-9_]*/)) {
return "variableName";
}
stream.next();
return null;
},
});
export default {
components: {
TabsRoot,
TabList,
TabTrigger,
TabContent,
CodeMirror,
},
props: {
yaml: {
type: String,
default: "",
},
env: {
type: String,
default: "",
},
fileName: {
type: String,
default: "compose.yaml",
},
editable: {
type: Boolean,
default: false,
},
disabled: {
type: Boolean,
default: false,
},
dirty: {
type: Boolean,
default: false,
},
},
emits: [ "update:yaml", "update:env", "save" ],
data() {
return {
activeFile: "yaml",
wrap: true,
fullscreen: false,
fullscreenAvailable: Boolean(document.fullscreenEnabled),
cursor: {
line: 1,
column: 1,
},
};
},
computed: {
yamlModel: {
get() {
return this.yaml;
},
set(value) {
this.$emit("update:yaml", value);
},
},
envModel: {
get() {
return this.env;
},
set(value) {
this.$emit("update:env", value);
},
},
yamlExtensions() {
return [ yamlLanguage(), ...(this.$root.isDark ? [ dracula ] : []) ];
},
envExtensions() {
return [ envLanguage, ...(this.$root.isDark ? [ dracula ] : []) ];
},
saveKeymap() {
return [
{
key: "Mod-s",
run: () => {
if (this.editable && !this.disabled) {
this.$emit("save");
}
return true;
},
},
indentWithTab,
];
},
yamlDiagnostics() {
return this.yamlIssues(this.yaml);
},
envDiagnostics() {
return analyzeEnv(this.env).map(issue => ({ ...issue,
message: this.$t(issue.message) }));
},
yamlErrorCount() {
return this.yamlDiagnostics.filter(issue => issue.severity === "error").length;
},
envErrorCount() {
return this.envDiagnostics.filter(issue => issue.severity === "error").length;
},
diagnostics() {
return [
...this.yamlDiagnostics.map(issue => ({ ...issue,
file: "yaml",
line: this.yaml.slice(0, issue.from).split("\n").length })),
...this.envDiagnostics.map(issue => ({ ...issue,
file: "env",
line: this.env.slice(0, issue.from).split("\n").length })),
];
},
},
watch: {
async activeFile() {
await nextTick();
const editor = this.currentEditor();
editor?.view?.requestMeasure();
if (editor?.view) {
this.updateCursor({ state: editor.view.state });
}
},
},
mounted() {
document.addEventListener("fullscreenchange", this.fullscreenChanged);
},
beforeUnmount() {
document.removeEventListener("fullscreenchange", this.fullscreenChanged);
},
methods: {
/** Build editor diagnostics without changing the YAML or its comments. */
yamlIssues(source) {
try {
const doc = parseDocument(source);
const issues = doc.errors.map(error => ({
from: Math.min(error.pos[0], source.length),
to: Math.min(error.pos[1], source.length),
severity: "error",
message: error.message,
}));
if (issues.length) {
return issues;
}
const config = doc.toJS();
if (config !== null && (typeof config !== "object" || Array.isArray(config))) {
issues.push({
from: 0,
to: 0,
severity: "error",
message: this.$t("editorYamlMapping"),
});
} else if (config?.services && (Array.isArray(config.services) || typeof config.services !== "object")) {
issues.push({
from: 0,
to: 0,
severity: "error",
message: this.$t("editorServicesMapping"),
});
}
return issues;
} catch (error) {
return [{
from: 0,
to: 0,
severity: "error",
message: error.message,
}];
}
},
/** Annotate YAML in the editor gutter. */
lintYAML(view) {
return this.yamlIssues(view.state.doc.toString());
},
/** Annotate dotenv syntax and duplicate definitions. */
lintEnv(view) {
return analyzeEnv(view.state.doc.toString()).map(issue => ({
...issue,
message: this.$t(issue.message),
}));
},
/** Select the active editor without remounting either file. */
currentEditor() {
return this.activeFile === "yaml" ? this.$refs.yamlEditor : this.$refs.envEditor;
},
/** Give the editable surface an accessible file name. */
labelEditor(file) {
const editor = file === "yaml" ? this.$refs.yamlEditor : this.$refs.envEditor;
editor?.view?.contentDOM.setAttribute("aria-label", file === "yaml" ? this.fileName : ".env");
},
/** Open CodeMirror's search and replace panel. */
find() {
const view = this.currentEditor()?.view;
if (view) {
openSearchPanel(view);
}
},
/** Format valid YAML while retaining comments and anchors. */
formatYAML() {
const doc = parseDocument(this.yaml);
if (!doc.errors.length) {
this.$emit("update:yaml", doc.toString({ indent: 2 }));
}
},
/** Display the cursor position for the active file. */
updateCursor(update, file = this.activeFile) {
if (file !== this.activeFile) {
return;
}
const position = update.state.selection.main.head;
const line = update.state.doc.lineAt(position);
this.cursor = { line: line.number,
column: position - line.from + 1 };
},
/** Move focus to the source location of a diagnostic. */
async jumpTo(issue) {
this.activeFile = issue.file;
await nextTick();
const view = this.currentEditor()?.view;
if (view) {
view.dispatch({ selection: { anchor: issue.from },
scrollIntoView: true });
view.focus();
}
},
/** Track native fullscreen, including the browser's Escape shortcut. */
fullscreenChanged() {
this.fullscreen = document.fullscreenElement === this.$refs.container;
},
/** Expand the editor using the browser's fullscreen focus handling. */
async toggleFullscreen() {
if (this.fullscreen) {
await document.exitFullscreen();
} else {
await this.$refs.container.requestFullscreen();
}
},
},
};
</script>
<style scoped lang="scss">
.stack-config-editor {
overflow: hidden;
border: 1px solid var(--stack-nav-colors-border);
border-radius: 0.875rem;
background: var(--stack-nav-colors-surface);
color: var(--stack-nav-colors-text);
}
.config-toolbar,
.config-tools,
.config-tab-list,
.config-status {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.375rem;
}
.config-toolbar {
justify-content: space-between;
padding: 0.5rem;
border-bottom: 1px solid var(--stack-nav-colors-border);
}
.config-tab,
.config-tool {
min-height: 2.25rem;
border: 1px solid transparent;
border-radius: 0.375rem;
padding: 0.25rem 0.5rem;
color: inherit;
background: transparent;
font-size: 0.8125rem;
}
.config-tab[data-selected] {
background: var(--stack-nav-colors-accent-subtle);
color: var(--stack-nav-colors-accent);
font-weight: 600;
}
.config-tool:hover {
background: var(--stack-nav-colors-subtle);
}
.config-tool:disabled {
opacity: 0.5;
}
.config-tab:focus-visible,
.config-tool:focus-visible,
.config-diagnostics button:focus-visible {
outline: 2px solid var(--stack-nav-colors-accent);
outline-offset: 1px;
}
.config-tab-content[hidden] {
display: none;
}
.config-tab-content :deep(.cm-editor) {
height: 28rem;
font-family: "JetBrains Mono", monospace;
font-size: 0.8125rem;
}
.config-tab-content :deep(.cm-scroller) {
overflow: auto;
}
.config-status {
justify-content: space-between;
padding: 0.5rem 0.75rem;
border-top: 1px solid var(--stack-nav-colors-border);
color: var(--stack-nav-colors-muted);
font-size: 0.75rem;
}
.config-diagnostics {
max-height: 10rem;
overflow: auto;
margin: 0;
padding: 0.5rem 0.75rem 0.5rem 1.75rem;
border-top: 1px solid var(--stack-nav-colors-border);
font-size: 0.8125rem;
button {
border: 0;
padding: 0.25rem;
color: inherit;
background: transparent;
text-align: start;
overflow-wrap: anywhere;
}
}
.config-error,
.config-error-count {
color: var(--stack-nav-colors-danger);
}
.stack-config-editor:fullscreen {
display: flex;
flex-direction: column;
padding: 1rem;
.config-tabs,
.config-tab-content,
.config-tab-content :deep(.vue-codemirror),
.config-tab-content :deep(.cm-editor) {
flex: 1;
min-height: 0;
}
.config-tabs,
.config-tab-content {
display: flex;
flex-direction: column;
}
.config-tab-content[hidden] {
display: none;
}
.config-tab-content :deep(.cm-editor) {
height: 100%;
}
}
@media (max-width: 600px) {
.config-toolbar {
align-items: stretch;
flex-direction: column;
}
}
</style>

View File

@ -1,217 +1,447 @@
<template> <template>
<nav class="stack-nav-panel" :aria-label="$t('stackListTitle')"> <div class="shadow-box mb-3" :style="boxStyle">
<div class="stack-nav-header"> <div class="list-header">
<slot name="title"> <div class="header-top">
<h2 class="stack-nav-title">{{ $t("stackListTitle") }}</h2> <!-- TODO -->
</slot> <button v-if="false" class="btn btn-outline-normal ms-2" :class="{ 'active': selectMode }" type="button" @click="selectMode = !selectMode">
<router-link to="/compose" class="stack-nav-button stack-nav-primary" @click.left.exact="$emit('navigate')"> {{ $t("Select") }}
<font-awesome-icon icon="plus" aria-hidden="true" /> {{ $t("stackListNew") }}
</router-link>
<slot name="close" />
</div>
<div class="stack-nav-controls">
<label class="stack-nav-field">
<span>{{ $t("stackListSearch") }}</span>
<span class="stack-nav-search">
<font-awesome-icon icon="search" aria-hidden="true" />
<input ref="search" v-model.trim="searchText" type="search" :placeholder="$t('stackListSearchPlaceholder')" autocomplete="off">
</span>
</label>
<div class="stack-nav-filters">
<div class="stack-nav-field">
<label :for="hostId">{{ $t("stackListHost") }}</label>
<select :id="hostId" v-model="host">
<option :value="null">{{ $t("stackListAllHosts") }}</option>
<option v-for="agent in agents" :key="agent.endpoint" :value="agent.endpoint">
{{ agent.name }}
</option>
</select>
</div>
<div class="stack-nav-field">
<label :for="statusId">{{ $t("stackListStatus") }}</label>
<select :id="statusId" v-model="status">
<option value="">{{ $t("stackListAllStatuses") }}</option>
<option v-for="option in statuses" :key="option" :value="option">
{{ $t(option) }}
</option>
</select>
</div>
</div>
</div>
<div class="stack-nav-summary">
<span role="status">{{ loading ? $t("stackListLoading") : $t("stackListCount", resultCount) }}</span>
<button v-if="filtersActive" type="button" class="stack-nav-reset" @click="clearFilters">
{{ $t("stackListResetFilters") }}
</button> </button>
<div class="placeholder"></div>
<div class="search-wrapper">
<a v-if="searchText == ''" class="search-icon">
<font-awesome-icon icon="search" />
</a>
<a v-if="searchText != ''" class="search-icon" style="cursor: pointer" @click="clearSearchText">
<font-awesome-icon icon="times" />
</a>
<form>
<input v-model="searchText" class="form-control search-input" autocomplete="off" />
</form>
</div>
</div> </div>
<div class="stack-nav-results"> <!-- TODO -->
<p v-if="!$root.socketIO.connected" class="stack-nav-message" role="status"> <div v-if="false" class="header-filter">
{{ $t("stackListStale") }} <!--<StackListFilter :filterState="filterState" @update-filter="updateFilter" />-->
</p> </div>
<div :key="filtersActive ? 'filtered' : 'all'">
<CollapsibleRoot <!-- TODO: Selection Controls -->
v-for="agent in visibleAgents" :key="agent.endpoint" class="stack-nav-group" :default-open="true" <div v-if="selectMode && false" class="selection-controls px-2 pt-2">
> <input
<CollapsibleTrigger v-if="agent.stacks.length" class="stack-nav-group-heading" type="button"> v-model="selectAll"
<font-awesome-icon icon="chevron-down" class="stack-nav-chevron" aria-hidden="true" /> class="form-check-input select-input"
<span class="stack-nav-agent">{{ agent.name }}</span> type="checkbox"
<span v-if="agent.connection !== 'online'" class="stack-nav-connection" :data-state="agent.connection"> />
{{ $t(agent.connection === "offline" ? "agentOffline" : "connecting") }}
</span> <button class="btn-outline-normal" @click="pauseDialog"><font-awesome-icon icon="pause" size="sm" /> {{ $t("Pause") }}</button>
</CollapsibleTrigger> <button class="btn-outline-normal" @click="resumeSelected"><font-awesome-icon icon="play" size="sm" /> {{ $t("Resume") }}</button>
<div v-else class="stack-nav-group-heading">
<span class="stack-nav-agent">{{ agent.name }}</span> <span v-if="selectedStackCount > 0">
<span class="stack-nav-connection" :data-state="agent.connection"> {{ $t("selectedStackCount", [ selectedStackCount ]) }}
{{ $t(agent.connection === "offline" ? "agentOffline" : "connecting") }}
</span> </span>
</div> </div>
<CollapsibleContent v-if="agent.stacks.length" as="ul" class="stack-nav-items">
<li v-for="stack in agent.stacks" :key="stack.name">
<StackListItem :stack="stack" :host-name="agent.name" @navigate="$emit('navigate')" />
</li>
</CollapsibleContent>
</CollapsibleRoot>
</div> </div>
<div v-if="emptyMessage" class="stack-nav-message"> <div ref="stackList" class="stack-list" :class="{ scrollbar: scrollbar }" :style="stackListStyle">
<p>{{ $t(emptyMessage) }}</p> <div v-if="Object.keys(sortedStackList).length === 0" class="text-center mt-3">
<router-link v-if="emptyMessage === 'stackListEmpty'" to="/compose" @click.left.exact="$emit('navigate')"> <router-link to="/compose">{{ $t("addFirstStackMsg") }}</router-link>
{{ $t("addFirstStackMsg") }} </div>
</router-link>
<StackListItem
v-for="(item, index) in sortedStackList"
:key="index"
:stack="item"
:isSelectMode="selectMode"
:isSelected="isSelected"
:select="select"
:deselect="deselect"
/>
</div> </div>
</div> </div>
</nav>
<Confirm ref="confirmPause" :yes-text="$t('Yes')" :no-text="$t('No')" @yes="pauseSelected">
{{ $t("pauseStackMsg") }}
</Confirm>
</template> </template>
<script> <script>
import { CollapsibleContent, CollapsibleRoot, CollapsibleTrigger } from "@ark-ui/vue/collapsible"; import Confirm from "../components/Confirm.vue";
import { useId } from "vue"; import StackListItem from "../components/StackListItem.vue";
import StackListItem from "./StackListItem.vue"; import { CREATED_FILE, CREATED_STACK, EXITED, RUNNING, UNKNOWN } from "../../../common/util-common";
import { CREATED_FILE, CREATED_STACK, EXITED, RUNNING, UNKNOWN, statusNameShort } from "../../../common/util-common";
const statuses = [ "active", "exited", "inactive", "stackListUnknown" ];
const statusOrder = [ RUNNING, EXITED, CREATED_STACK, CREATED_FILE, UNKNOWN ];
export default { export default {
components: { components: {
CollapsibleContent, Confirm,
CollapsibleRoot,
CollapsibleTrigger,
StackListItem, StackListItem,
}, },
emits: [ "navigate" ], props: {
setup() { /** Should the scrollbar be shown */
return { scrollbar: {
hostId: useId(), type: Boolean,
statusId: useId(), },
};
}, },
data() { data() {
return { return {
searchText: "", searchText: "",
host: null, selectMode: false,
status: "", selectAll: false,
statuses, disableSelectAllWatcher: false,
selectedStacks: {},
windowTop: 0,
filterState: {
status: null,
active: null,
tags: null,
}
}; };
}, },
computed: { computed: {
agents() {
const agents = new Map();
const endpoints = [ "", ...Object.keys(this.$root.agentList).filter(Boolean) ];
for (const endpoint of endpoints) {
agents.set(endpoint, this.describeAgent(endpoint));
}
for (const stack of Object.values(this.$root.completeStackList)) {
const endpoint = stack.endpoint || "";
if (!agents.has(endpoint)) {
agents.set(endpoint, this.describeAgent(endpoint));
}
agents.get(endpoint).stacks.push(stack);
}
const [ local, ...remote ] = agents.values();
remote.sort((a, b) => a.name.localeCompare(b.name));
return [ local, ...remote ];
},
filteredAgents() {
const query = this.searchText.toLowerCase();
return this.agents.filter(agent => this.host === null || agent.endpoint === this.host).map(agent => {
const stacks = agent.stacks.filter(stack => {
const status = statusNameShort(stack.status);
if (this.status && (status === "?" ? "stackListUnknown" : status) !== this.status) {
return false;
}
return !query || stack.name.toLowerCase().includes(query)
|| stack.tags?.some(tag => tag.name.toLowerCase().includes(query) || tag.value?.toLowerCase().includes(query));
});
stacks.sort((a, b) => Number(b.isManagedByDockge) - Number(a.isManagedByDockge)
|| statusOrder.indexOf(a.status) - statusOrder.indexOf(b.status) || a.name.localeCompare(b.name));
return { ...agent,
stacks };
});
},
visibleAgents() {
return this.filteredAgents.filter(agent => agent.stacks.length || agent.connection !== "online");
},
resultCount() {
return this.filteredAgents.reduce((total, agent) => total + agent.stacks.length, 0);
},
loading() {
return this.filteredAgents.some(agent => agent.connection !== "offline" && !agent.loaded);
},
filtersActive() {
return this.host !== null || Boolean(this.status || this.searchText);
},
emptyMessage() {
if (this.loading || this.resultCount || !this.$root.socketIO.connected) {
return "";
}
if (this.searchText || this.status) {
return "stackListNoMatches";
}
if (this.visibleAgents.length) {
return "";
}
return this.host === null ? "stackListEmpty" : "stackListHostEmpty";
},
},
watch: {
agents(agents) {
if (this.host !== null && !agents.some(agent => agent.endpoint === this.host)) {
this.host = null;
}
},
},
methods: {
/** /**
* Build the label and connection state for an agent, including agents without stacks. * Improve the sticky appearance of the list by increasing its
* @param {string} endpoint Agent endpoint, or an empty string for the local host * height as user scrolls down.
* @returns {object} Agent shown in the stack navigator * Not used on mobile.
* @returns {object} Style for stack list
*/ */
describeAgent(endpoint) { boxStyle() {
const loaded = endpoint ? Object.hasOwn(this.$root.allAgentStackList, endpoint) : this.$root.stackListLoaded; if (window.innerWidth > 550) {
return { return {
endpoint, height: `calc(100vh - 160px + ${this.windowTop}px)`,
name: endpoint ? this.$root.agentList[endpoint]?.name || endpoint : this.$t("stackListLocal"), };
connection: this.$root.agentStatusList[endpoint] || (loaded ? "online" : "connecting"), } else {
loaded, return {
stacks: [], height: "calc(100vh - 160px)",
};
}
},
/**
* Returns a sorted list of stacks based on the applied filters and search text.
* @returns {Array} The sorted list of stacks.
*/
sortedStackList() {
let result = Object.values(this.$root.completeStackList);
result = result.filter(stack => {
// filter by search text
// finds stack name, tag name or tag value
let searchTextMatch = true;
if (this.searchText !== "") {
const loweredSearchText = this.searchText.toLowerCase();
searchTextMatch =
stack.name.toLowerCase().includes(loweredSearchText)
|| stack.tags.find(tag => tag.name.toLowerCase().includes(loweredSearchText)
|| tag.value?.toLowerCase().includes(loweredSearchText));
}
// filter by active
let activeMatch = true;
if (this.filterState.active != null && this.filterState.active.length > 0) {
activeMatch = this.filterState.active.includes(stack.active);
}
// filter by tags
let tagsMatch = true;
if (this.filterState.tags != null && this.filterState.tags.length > 0) {
tagsMatch = stack.tags.map(tag => tag.tag_id) // convert to array of tag IDs
.filter(stackTagId => this.filterState.tags.includes(stackTagId)) // perform Array Intersaction between filter and stack's tags
.length > 0;
}
return searchTextMatch && activeMatch && tagsMatch;
});
result.sort((m1, m2) => {
// sort by managed by dockge
if (m1.isManagedByDockge && !m2.isManagedByDockge) {
return -1;
} else if (!m1.isManagedByDockge && m2.isManagedByDockge) {
return 1;
}
// sort by status
if (m1.status !== m2.status) {
if (m2.status === RUNNING) {
return 1;
} else if (m1.status === RUNNING) {
return -1;
} else if (m2.status === EXITED) {
return 1;
} else if (m1.status === EXITED) {
return -1;
} else if (m2.status === CREATED_STACK) {
return 1;
} else if (m1.status === CREATED_STACK) {
return -1;
} else if (m2.status === CREATED_FILE) {
return 1;
} else if (m1.status === CREATED_FILE) {
return -1;
} else if (m2.status === UNKNOWN) {
return 1;
} else if (m1.status === UNKNOWN) {
return -1;
}
}
return m1.name.localeCompare(m2.name);
});
return result;
},
isDarkTheme() {
return document.body.classList.contains("dark");
},
stackListStyle() {
//let listHeaderHeight = 107;
let listHeaderHeight = 60;
if (this.selectMode) {
listHeaderHeight += 42;
}
return {
"height": `calc(100% - ${listHeaderHeight}px)`
}; };
}, },
selectedStackCount() {
return Object.keys(this.selectedStacks).length;
},
/** /**
* Restore the unfiltered list. * Determines if any filters are active.
* @returns {boolean} True if any filter is active, false otherwise.
*/
filtersActive() {
return this.filterState.status != null || this.filterState.active != null || this.filterState.tags != null || this.searchText !== "";
}
},
watch: {
searchText() {
for (let stack of this.sortedStackList) {
if (!this.selectedStacks[stack.id]) {
if (this.selectAll) {
this.disableSelectAllWatcher = true;
this.selectAll = false;
}
break;
}
}
},
selectAll() {
if (!this.disableSelectAllWatcher) {
this.selectedStacks = {};
if (this.selectAll) {
this.sortedStackList.forEach((item) => {
this.selectedStacks[item.id] = true;
});
}
} else {
this.disableSelectAllWatcher = false;
}
},
selectMode() {
if (!this.selectMode) {
this.selectAll = false;
this.selectedStacks = {};
}
},
},
mounted() {
window.addEventListener("scroll", this.onScroll);
},
beforeUnmount() {
window.removeEventListener("scroll", this.onScroll);
},
methods: {
/**
* Handle user scroll
* @returns {void} * @returns {void}
*/ */
clearFilters() { onScroll() {
if (window.top.scrollY <= 133) {
this.windowTop = window.top.scrollY;
} else {
this.windowTop = 133;
}
},
/**
* Clear the search bar
* @returns {void}
*/
clearSearchText() {
this.searchText = ""; this.searchText = "";
this.host = null; },
this.status = ""; /**
this.$refs.search.focus(); * Update the StackList Filter
* @param {object} newFilter Object with new filter
* @returns {void}
*/
updateFilter(newFilter) {
this.filterState = newFilter;
},
/**
* Deselect a stack
* @param {number} id ID of stack
* @returns {void}
*/
deselect(id) {
delete this.selectedStacks[id];
},
/**
* Select a stack
* @param {number} id ID of stack
* @returns {void}
*/
select(id) {
this.selectedStacks[id] = true;
},
/**
* Determine if stack is selected
* @param {number} id ID of stack
* @returns {bool} Is the stack selected?
*/
isSelected(id) {
return id in this.selectedStacks;
},
/**
* Disable select mode and reset selection
* @returns {void}
*/
cancelSelectMode() {
this.selectMode = false;
this.selectedStacks = {};
},
/**
* Show dialog to confirm pause
* @returns {void}
*/
pauseDialog() {
this.$refs.confirmPause.show();
},
/**
* Pause each selected stack
* @returns {void}
*/
pauseSelected() {
Object.keys(this.selectedStacks)
.filter(id => this.$root.stackList[id].active)
.forEach(id => this.$root.getSocket().emit("pauseStack", id, () => {}));
this.cancelSelectMode();
},
/**
* Resume each selected stack
* @returns {void}
*/
resumeSelected() {
Object.keys(this.selectedStacks)
.filter(id => !this.$root.stackList[id].active)
.forEach(id => this.$root.getSocket().emit("resumeStack", id, () => {}));
this.cancelSelectMode();
}, },
}, },
}; };
</script> </script>
<style lang="scss" scoped>
@import "../styles/vars.scss";
.shadow-box {
height: calc(100vh - 150px);
position: sticky;
top: 10px;
}
.small-padding {
padding-left: 5px !important;
padding-right: 5px !important;
}
.list-header {
border-bottom: 1px solid #dee2e6;
border-radius: 10px 10px 0 0;
margin: -10px;
margin-bottom: 10px;
padding: 10px;
.dark & {
background-color: $dark-header-bg;
border-bottom: 0;
}
}
.header-top {
display: flex;
justify-content: space-between;
align-items: center;
}
.header-filter {
display: flex;
align-items: center;
}
@media (max-width: 770px) {
.list-header {
margin: -20px;
margin-bottom: 10px;
padding: 5px;
}
}
.search-wrapper {
display: flex;
align-items: center;
}
.search-icon {
padding: 10px;
color: #c0c0c0;
// Clear filter button (X)
svg[data-icon="times"] {
cursor: pointer;
transition: all ease-in-out 0.1s;
&:hover {
opacity: 0.5;
}
}
}
.search-input {
max-width: 15em;
}
.stack-item {
width: 100%;
}
.tags {
margin-top: 4px;
padding-left: 67px;
display: flex;
flex-wrap: wrap;
gap: 0;
}
.bottom-style {
padding-left: 67px;
margin-top: 5px;
}
.selection-controls {
margin-top: 5px;
display: flex;
align-items: center;
gap: 10px;
}
</style>

View File

@ -1,43 +1,181 @@
<template> <template>
<router-link :to="url" class="stack-nav-item" @click.left.exact="$emit('navigate')"> <router-link :to="url" :class="{ 'dim' : !stack.isManagedByDockge }" class="item">
<span class="stack-nav-item-copy"> <Uptime :stack="stack" :fixed-width="true" class="me-2" />
<span class="stack-nav-name">{{ stack.name }}</span> <div class="title">
<span class="stack-nav-item-meta"> <span>{{ stackName }}</span>
{{ hostName }}<template v-if="!stack.isManagedByDockge"> · {{ $t("stackListUnmanaged") }}</template> <div v-if="$root.agentCount > 1" class="endpoint">{{ endpointDisplay }}</div>
</span> </div>
</span>
<span class="stack-nav-badge" :data-state="status">
{{ $t(status) }}
</span>
</router-link> </router-link>
</template> </template>
<script> <script>
import { statusNameShort } from "../../../common/util-common"; import Uptime from "./Uptime.vue";
export default { export default {
components: {
Uptime
},
props: { props: {
/** Stack to link to */ /** Stack this represents */
stack: { stack: {
type: Object, type: Object,
required: true, default: null,
}, },
/** Display name of the host running the stack */ /** If the user is in select mode */
hostName: { isSelectMode: {
type: String, type: Boolean,
required: true, default: false,
},
/** How many ancestors are above this stack */
depth: {
type: Number,
default: 0,
},
/** Callback to determine if stack is selected */
isSelected: {
type: Function,
default: () => {}
},
/** Callback fired when stack is selected */
select: {
type: Function,
default: () => {}
},
/** Callback fired when stack is deselected */
deselect: {
type: Function,
default: () => {}
}, },
}, },
emits: [ "navigate" ], data() {
return {
isCollapsed: true,
};
},
computed: { computed: {
status() { endpointDisplay() {
const status = statusNameShort(this.stack.status); return this.$root.endpointDisplayFunction(this.stack.endpoint);
return status === "?" ? "stackListUnknown" : status;
}, },
url() { url() {
const name = encodeURIComponent(this.stack.name); if (this.stack.endpoint) {
return this.stack.endpoint ? `/compose/${name}/${encodeURIComponent(this.stack.endpoint)}` : `/compose/${name}`; return `/compose/${this.stack.name}/${this.stack.endpoint}`;
} else {
return `/compose/${this.stack.name}`;
}
},
depthMargin() {
return {
marginLeft: `${31 * this.depth}px`,
};
},
stackName() {
return this.stack.name;
}
},
watch: {
isSelectMode() {
// TODO: Resize the heartbeat bar, but too slow
// this.$refs.heartbeatBar.resize();
}
},
beforeMount() {
},
methods: {
/**
* Changes the collapsed value of the current stack and saves
* it to local storage
* @returns {void}
*/
changeCollapsed() {
this.isCollapsed = !this.isCollapsed;
// Save collapsed value into local storage
let storage = window.localStorage.getItem("stackCollapsed");
let storageObject = {};
if (storage !== null) {
storageObject = JSON.parse(storage);
}
storageObject[`stack_${this.stack.id}`] = this.isCollapsed;
window.localStorage.setItem("stackCollapsed", JSON.stringify(storageObject));
},
/**
* Toggle selection of stack
* @returns {void}
*/
toggleSelection() {
if (this.isSelected(this.stack.id)) {
this.deselect(this.stack.id);
} else {
this.select(this.stack.id);
}
}, },
}, },
}; };
</script> </script>
<style lang="scss" scoped>
@import "../styles/vars.scss";
.small-padding {
padding-left: 5px !important;
padding-right: 5px !important;
}
.collapse-padding {
padding-left: 8px !important;
padding-right: 2px !important;
}
.item {
text-decoration: none;
display: flex;
align-items: center;
min-height: 52px;
border-radius: 10px;
transition: all ease-in-out 0.15s;
width: 100%;
padding: 5px 8px;
&.disabled {
opacity: 0.3;
}
&:hover {
background-color: $highlight-white;
}
&.active {
background-color: #cdf8f4;
}
.title {
margin-top: -4px;
}
.endpoint {
font-size: 12px;
color: $dark-font-color3;
}
}
.collapsed {
transform: rotate(-90deg);
}
.animated {
transition: all 0.2s $easing-in;
}
.select-input-wrapper {
float: left;
margin-top: 15px;
margin-left: 3px;
margin-right: 10px;
padding-left: 4px;
position: relative;
z-index: 15;
}
.dim {
opacity: 0.5;
}
</style>

View File

@ -20,24 +20,22 @@ export default {
props: { props: {
name: { name: {
type: String, type: String,
required: true, require: true,
}, },
endpoint: { endpoint: {
type: String, type: String,
required: true, require: true,
}, },
// Require if mode is interactive // Require if mode is interactive
stackName: { stackName: {
type: String, type: String,
default: "",
}, },
// Require if mode is interactive // Require if mode is interactive
serviceName: { serviceName: {
type: String, type: String,
default: "",
}, },
// Require if mode is interactive // Require if mode is interactive
@ -104,7 +102,7 @@ export default {
this.terminal.focus(); this.terminal.focus();
// Add right-click context menu handler for paste // Add right-click context menu handler for paste
this.$refs.terminal.addEventListener("contextmenu", this.handleContextMenu); this.$refs.terminal.addEventListener('contextmenu', this.handleContextMenu);
// Add selection handler for copy to clipboard // Add selection handler for copy to clipboard
this.terminal.onSelectionChange(() => { this.terminal.onSelectionChange(() => {
@ -145,7 +143,7 @@ export default {
window.removeEventListener("resize", this.onResizeEvent); // Remove the resize event listener from the window object. window.removeEventListener("resize", this.onResizeEvent); // Remove the resize event listener from the window object.
this.$root.unbindTerminal(this.name); this.$root.unbindTerminal(this.name);
this.terminal.dispose(); this.terminal.dispose();
this.$refs.terminal?.removeEventListener("contextmenu", this.handleContextMenu); this.$refs.terminal?.removeEventListener('contextmenu', this.handleContextMenu);
}, },
methods: { methods: {

View File

@ -57,8 +57,7 @@ export default {
EditorView.focusChangeEffect.of(focusEffectHandler), EditorView.focusChangeEffect.of(focusEffectHandler),
]; ];
return { editorFocus, return { editorFocus, extensionsEnv };
extensionsEnv };
}, },
computed: { computed: {

View File

@ -94,18 +94,10 @@
<TwoFADialog ref="TwoFADialog" /> <TwoFADialog ref="TwoFADialog" />
<Confirm ref="confirmDisableAuth" btn-style="btn-danger" :yes-text="$t('I understand, please disable')" :no-text="$t('Leave')" @yes="disableAuth"> <Confirm ref="confirmDisableAuth" btn-style="btn-danger" :yes-text="$t('I understand, please disable')" :no-text="$t('Leave')" @yes="disableAuth">
<i18n-t keypath="disableauth.message1" tag="p"> <!-- eslint-disable-next-line vue/no-v-html -->
<template #disableAuth> <p v-html="$t('disableauth.message1')"></p>
<strong>{{ $t('disableAuth') }}</strong> <!-- eslint-disable-next-line vue/no-v-html -->
</template> <p v-html="$t('disableauth.message2')"></p>
</i18n-t>
<i18n-t keypath="disableauth.message2" tag="p">
<template #scenarios>
<strong>{{ $t('scenarios') }}</strong>
</template>
</i18n-t>
<p>{{ $t("Please use this option carefully!") }}</p> <p>{{ $t("Please use this option carefully!") }}</p>
<div class="mb-3"> <div class="mb-3">
@ -184,23 +176,23 @@ export default {
/** Disable authentication for web app access */ /** Disable authentication for web app access */
disableAuth() { disableAuth() {
this.settings.disableAuth = true;
// Need current password to disable auth // Need current password to disable auth
// Set it to empty if done // Set it to empty if done
this.saveSettings(() => { this.saveSettings(() => {
this.password.currentPassword = ""; this.password.currentPassword = "";
this.$root.username = null; this.$root.username = null;
}, this.password.currentPassword, true); this.$root.socketIO.token = "autoLogin";
}, this.password.currentPassword);
}, },
/** Enable authentication for web app access */ /** Enable authentication for web app access */
enableAuth() { enableAuth() {
this.saveSettings(() => { this.settings.disableAuth = false;
if (this.$root.socketIO.token === "autoLogin") { this.saveSettings();
this.$root.finishLogout(); this.$root.storage().removeItem("token");
} else { location.reload();
this.$root.logout();
}
}, undefined, false);
}, },
/** Show confirmation dialog for disable auth */ /** Show confirmation dialog for disable auth */

View File

@ -38,7 +38,6 @@ import {
faAward, faAward,
faLink, faLink,
faChevronDown, faChevronDown,
faChevronUp,
faSignOutAlt, faSignOutAlt,
faPen, faPen,
faExternalLinkSquareAlt, faExternalLinkSquareAlt,
@ -55,8 +54,6 @@ import {
faTerminal, faWarehouse, faHome, faRocket, faTerminal, faWarehouse, faHome, faRocket,
faRotate, faRotate,
faCloudArrowDown, faArrowsRotate, faCloudArrowDown, faArrowsRotate,
faChevronCircleRight,
faChevronCircleDown,
} from "@fortawesome/free-solid-svg-icons"; } from "@fortawesome/free-solid-svg-icons";
library.add( library.add(
@ -91,7 +88,6 @@ library.add(
faAward, faAward,
faLink, faLink,
faChevronDown, faChevronDown,
faChevronUp,
faSignOutAlt, faSignOutAlt,
faPen, faPen,
faExternalLinkSquareAlt, faExternalLinkSquareAlt,
@ -113,8 +109,6 @@ library.add(
faRotate, faRotate,
faCloudArrowDown, faCloudArrowDown,
faArrowsRotate, faArrowsRotate,
faChevronCircleRight,
faChevronCircleDown,
); );
export { FontAwesomeIcon }; export { FontAwesomeIcon };

View File

@ -12,125 +12,17 @@
"registry": "Registry", "registry": "Registry",
"compose": "Compose", "compose": "Compose",
"addFirstStackMsg": "Compose your first stack!", "addFirstStackMsg": "Compose your first stack!",
"stackListTitle": "Stacks",
"stackListNew": "New stack",
"stackListSearch": "Search stacks",
"stackListSearchPlaceholder": "Name or tag",
"stackListHost": "Host",
"stackListAllHosts": "All hosts",
"stackListStatus": "Status",
"stackListAllStatuses": "All statuses",
"stackListUnknown": "Unknown",
"stackListLocal": "Local host",
"stackListUnmanaged": "Unmanaged",
"stackListEmpty": "No stacks yet.",
"stackListHostEmpty": "No stacks on this host.",
"stackListNoMatches": "No matching stacks.",
"stackListLoading": "Loading stacks…",
"stackListStale": "Connection lost. Status may be out of date.",
"stackListResetFilters": "Clear filters",
"stackListClose": "Close stack list",
"stackListCount": "No stacks | 1 stack | {count} stacks",
"stackName": "Stack Name", "stackName": "Stack Name",
"deployStack": "Deploy", "deployStack": "Deploy",
"deleteStack": "Delete", "deleteStack": "Delete",
"stopStack": "Stop", "stopStack": "Stop",
"restartStack": "Restart", "restartStack": "Restart",
"updateStack": "Update", "updateStack": "Update",
"autoUpdateTitle": "Automatic image updates",
"imageScanTitle": "Image vulnerabilities",
"imageScanDescription": "On-demand Grype scan of the images used by this stack's containers. The scan may download vulnerability database updates.",
"imageScanStart": "Scan images",
"imageScanRefresh": "Refresh scan",
"imageScanProgress": "Scanning images · {completed} / {total} finished",
"imageScanNotRun": "No scan results available.",
"imageScanNoImages": "No images found for this stack's containers.",
"imageScanImage": "Image",
"imageScanSeverityLabel": "Severity",
"imageScanCounts": "Findings by severity",
"imageScanAllSeverities": "All severities",
"imageScanFindings": "Reported vulnerabilities for the selected image",
"imageScanAdvisory": "Advisory",
"imageScanPackage": "Package",
"imageScanInstalled": "Installed",
"imageScanFixed": "Fixed in",
"imageScanFixUnknown": "No fix version reported",
"imageScanNoFindings": "No findings reported for this filter.",
"imageScanLoading": "Loading findings…",
"imageScanPrevious": "Previous",
"imageScanNext": "Next",
"imageScanPage": "{first}–{last} of {total}",
"imageScanTimestamp": "Snapshot from {time}",
"imageScanDatabase": "Vulnerability database built {time}",
"imageScanTruncated": "The 500 highest-severity findings are retained for this image. Counts include all reported findings.",
"imageScanRetention": "Results describe the scanned image IDs. Dockge keeps the latest scan for up to eight stacks until it restarts.",
"imageScanHostBusy": "Another image scan is running on this host. Try again when it finishes.",
"imageScanInvalidRequest": "Invalid image scan request.",
"imageScanReportChanged": "This scan result has changed or expired. Refresh the scan view.",
"imageScanRequestFailed": "Dockge could not load the scan state. Check the connection and refresh the scan view.",
"imageScanFailed": "The image scan failed. Check the Docker connection and scanner configuration.",
"imageScanDiscoveryFailed": "Dockge could not identify this stack's local container images.",
"imageScanTooManyImages": "A scan supports up to 20 distinct images per stack.",
"imageScanImageTooLarge": "This image exceeds the 1 GiB scan size limit.",
"imageScanExportFailed": "Docker could not export this image.",
"imageScanImageFailed": "The image scan failed or timed out. Check the Grype installation, database access, and available disk space.",
"imageScanInvalidReport": "Grype returned an invalid or unsupported report.",
"imageScanScannerUnavailable": "Install Grype on this host to enable scanning. New Dockge images include Grype on amd64 and arm64. Native installations can set DOCKGE_GRYPE_PATH to the executable.",
"imageScanStatus": {
"pending": "Pending",
"scanned": "Scanned",
"failed": "Failed"
},
"imageScanSeverity": {
"critical": "Critical",
"high": "High",
"medium": "Medium",
"low": "Low",
"negligible": "Negligible",
"unknown": "Unknown"
},
"autoUpdateEnable": "Enable automatic updates for this stack",
"autoUpdateDescription": "Daily at 04:00 UTC. Dockge can restart running services when their images change. Services with undeployed configuration changes are skipped.",
"autoUpdateLastRun": "Last run: {time} · {result}",
"autoUpdateSaveFailed": "Dockge could not confirm the automatic update setting. Reopen this stack to check it.",
"autoUpdateResult": {
"updated": "Image updates applied",
"unchanged": "Eligible images up to date",
"skipped": "No eligible services",
"failed": "Update failed. See the Dockge server logs."
},
"startStack": "Start", "startStack": "Start",
"downStack": "Stop & Inactive", "downStack": "Stop & Inactive",
"editStack": "Edit", "editStack": "Edit",
"discardStack": "Discard", "discardStack": "Discard",
"saveStackDraft": "Save", "saveStackDraft": "Save",
"editorTitle": "Stack configuration editor",
"editorFiles": "Configuration files",
"editorFind": "Find",
"editorFormat": "Format YAML",
"editorWrap": "Line wrap",
"editorFullscreen": "Fullscreen",
"editorExitFullscreen": "Exit fullscreen",
"editorUnsaved": "Unsaved changes",
"editorSaved": "Saved",
"editorReadOnly": "Read only",
"editorCursor": "Ln {line}, Col {column}",
"editorLine": "Line {line}",
"editorSaveShortcut": "Ctrl/Cmd+S to save",
"editorDiagnostics": "Configuration diagnostics",
"editorYamlMapping": "The Compose document must be a YAML mapping.",
"editorServicesMapping": "Services must be a mapping of service names to settings.",
"editorEnvDuplicate": "This variable is defined more than once. Later definitions take precedence.",
"editorEnvUnclosedQuote": "This quoted value is not closed.",
"editorEnvNull": "An environment file cannot contain a NUL character.",
"editorInvalidEnv": "Fix the environment file errors before saving.",
"editorConflict": "The configuration changed on the host. Your edits are still here. Discard them to load the saved version, or copy them before reloading.",
"editorSaveFailed": "Dockge could not save this configuration.",
"editorSaveUnconfirmed": "The host did not confirm the save. Your edits are still here. Retry saving or reload the stack to check the saved version.",
"editorComposeInvalid": "Docker Compose validation failed. Check the progress output for details.",
"editorFileConflict": "Compose and .env resolve to the same file. Save them to separate files.",
"editorFileNotRegular": "The configuration path must point to a regular file.",
"editorSaveRecoveryFailed": "Saving failed and automatic recovery was incomplete. Check the .dockge-*.bak files alongside the affected configuration files before retrying.",
"notAvailableShort": "N/A", "notAvailableShort": "N/A",
"deleteStackMsg": "Are you sure you want to delete this stack?", "deleteStackMsg": "Are you sure you want to delete this stack?",
"cancel": "Cancel", "cancel": "Cancel",
@ -155,10 +47,8 @@
"deleteContainer": "Delete", "deleteContainer": "Delete",
"addContainer": "Add Container", "addContainer": "Add Container",
"addNetwork": "Add Network", "addNetwork": "Add Network",
"disableauth.message1": "Are you sure want to {disableAuth}?", "disableauth.message1": "Are you sure want to <strong>disable authentication</strong>?",
"disableauth.message2": "It is designed for scenarios {scenarios}", "disableauth.message2": "It is designed for scenarios <strong>where you intend to implement third-party authentication</strong> in front of Dockge such as Cloudflare Access, Authelia or other authentication mechanisms.",
"disableAuth": "disable authentication",
"scenarios": "where you intend to implement third-party authentication",
"passwordNotMatchMsg": "The repeat password does not match.", "passwordNotMatchMsg": "The repeat password does not match.",
"autoGet": "Auto Get", "autoGet": "Auto Get",
"add": "Add", "add": "Add",
@ -190,7 +80,6 @@
"Password": "Password", "Password": "Password",
"Settings": "Settings", "Settings": "Settings",
"Logout": "Logout", "Logout": "Logout",
"authLogoutFailed": "Dockge could not confirm that this session ended. Please try again while connected.",
"Lowercase only": "Lowercase only", "Lowercase only": "Lowercase only",
"Convert to Compose": "Convert to Compose", "Convert to Compose": "Convert to Compose",
"Docker Run": "Docker Run", "Docker Run": "Docker Run",
@ -227,8 +116,6 @@
"removeAgentMsg": "Are you sure you want to remove this agent?", "removeAgentMsg": "Are you sure you want to remove this agent?",
"GlobalEnv": "Global .env", "GlobalEnv": "Global .env",
"LongSyntaxNotSupported": "Long syntax is not supported here. Please use the YAML editor.", "LongSyntaxNotSupported": "Long syntax is not supported here. Please use the YAML editor.",
"name": "Dockge Agent Display name",
"updatedName": "New Dockge Agent Display name",
"Saved": "Saved", "Saved": "Saved",
"Deployed": "Deployed", "Deployed": "Deployed",
"Deleted": "Deleted", "Deleted": "Deleted",
@ -244,18 +131,9 @@
"Network name...": "Network name...", "Network name...": "Network name...",
"Select a network...": "Select a network...", "Select a network...": "Select a network...",
"NoNetworksAvailable": "No networks available. You need to add internal networks or enable external networks in the right side first.", "NoNetworksAvailable": "No networks available. You need to add internal networks or enable external networks in the right side first.",
"CPU": "CPU",
"memory": "Memory",
"memoryAbbreviated": "Mem",
"networkIO": "Network I/O",
"blockIO": "Block I/O",
"Console is not enabled": "Console is not enabled", "Console is not enabled": "Console is not enabled",
"ConsoleNotEnabledMSG1": "Console is a powerful tool that allows you to execute any commands such as {docker}, {rm} within the Dockge's container in this Web UI.", "ConsoleNotEnabledMSG1": "Console is a powerful tool that allows you to execute any commands such as <code>docker</code>, <code>rm</code> within the Dockge's container in this Web UI.",
"ConsoleNotEnabledMSG2": "It might be dangerous since this Dockge container is connecting to the host's Docker daemon. Also Dockge could be possibly taken down by commands like {rmRf}", "ConsoleNotEnabledMSG2": "It might be dangerous since this Dockge container is connecting to the host's Docker daemon. Also Dockge could be possibly taken down by commands like <code>rm -rf</code>" ,
"ConsoleNotEnabledMSG3": "If you understand the risk, you can enable it by setting {envVar} in the environment variables.", "ConsoleNotEnabledMSG3": "If you understand the risk, you can enable it by setting <code>DOCKGE_ENABLE_CONSOLE=true</code> in the environment variables.",
"dockerCode": "docker",
"rmCode": "rm",
"rmRfCode": "rm -rf",
"envVarCode": "DOCKGE_ENABLE_CONSOLE=true",
"confirmLeaveStack": "You are currently editing a stack. Are you sure you want to leave?" "confirmLeaveStack": "You are currently editing a stack. Are you sure you want to leave?"
} }

View File

@ -13,8 +13,7 @@ export default defineComponent({
data() { data() {
return { return {
socketIO: { socketIO: {
token: null as string | null, token: null,
logoutPending: false,
firstConnect: true, firstConnect: true,
connected: false, connected: false,
connectCount: 0, connectCount: 0,
@ -33,7 +32,6 @@ export default defineComponent({
composeTemplate: "", composeTemplate: "",
stackList: {}, stackList: {},
stackListLoaded: false,
// All stack list from all agents // All stack list from all agents
allAgentStackList: {} as Record<string, object>, allAgentStackList: {} as Record<string, object>,
@ -133,15 +131,10 @@ export default defineComponent({
methods: { methods: {
endpointDisplayFunction(endpoint : string) { endpointDisplayFunction(endpoint : string) {
for (const [ k, v ] of Object.entries(this.$data.agentList)) {
if (endpoint) { if (endpoint) {
if (endpoint === v["endpoint"] && v["name"] !== "") {
return v["name"];
}
if (endpoint === v["endpoint"] && v["name"] === "" ) {
return endpoint; return endpoint;
} } else {
} return this.$t("currentEndpoint");
} }
}, },
@ -186,7 +179,7 @@ export default defineComponent({
this.socketIO.connectCount++; this.socketIO.connectCount++;
this.socketIO.connected = true; this.socketIO.connected = true;
this.socketIO.showReverseProxyGuide = false; this.socketIO.showReverseProxyGuide = false;
const token = this.socketIO.token ?? this.storage().token; const token = this.storage().token;
if (token) { if (token) {
if (token !== "autoLogin") { if (token !== "autoLogin") {
@ -255,7 +248,6 @@ export default defineComponent({
if (res.ok) { if (res.ok) {
if (!res.endpoint) { if (!res.endpoint) {
this.stackList = res.stackList; this.stackList = res.stackList;
this.stackListLoaded = true;
} else { } else {
if (!this.allAgentStackList[res.endpoint]) { if (!this.allAgentStackList[res.endpoint]) {
this.allAgentStackList[res.endpoint] = { this.allAgentStackList[res.endpoint] = {
@ -295,10 +287,6 @@ export default defineComponent({
socket.on("refresh", () => { socket.on("refresh", () => {
location.reload(); location.reload();
}); });
socket.on("sessionRevoked", () => {
this.finishLogout();
});
}, },
/** /**
@ -318,11 +306,11 @@ export default defineComponent({
}, },
/** /**
* Get the payload of the active session token * Get payload of JWT cookie
* @returns {(object | undefined)} JWT payload * @returns {(object | undefined)} JWT payload
*/ */
getJWTPayload() { getJWTPayload() {
const jwtToken = this.socketIO.token; const jwtToken = this.storage().token;
if (jwtToken && jwtToken !== "autoLogin") { if (jwtToken && jwtToken !== "autoLogin") {
return jwtDecode(jwtToken); return jwtDecode(jwtToken);
@ -374,9 +362,8 @@ export default defineComponent({
this.allowLoginDialog = true; this.allowLoginDialog = true;
if (! res.ok) { if (! res.ok) {
this.finishLogout(token); this.logout();
} else { } else {
this.socketIO.token = token;
this.loggedIn = true; this.loggedIn = true;
this.username = this.getJWTPayload()?.username; this.username = this.getJWTPayload()?.username;
this.afterLogin(); this.afterLogin();
@ -385,57 +372,23 @@ export default defineComponent({
}, },
/** /**
* Ask the server to revoke this session before removing its credentials. * Log out of the web application
* @returns {Promise<void>}
*/
async logout() {
if (this.socketIO.logoutPending) {
return;
}
if (!socket.connected) {
this.toastError("authLogoutFailed");
return;
}
this.socketIO.logoutPending = true;
try {
const res = await socket.timeout(5000).emitWithAck("logout");
if (res.ok) {
this.finishLogout();
} else {
this.toastRes(res);
}
} catch {
this.toastError("authLogoutFailed");
} finally {
this.socketIO.logoutPending = false;
}
},
/**
* Remove the current session from the browser after rejection or revocation.
* @param {string | null} token Token associated with the session being cleared
* @returns {void} * @returns {void}
*/ */
finishLogout(token = this.socketIO.token) { logout() {
socket.disconnect(); socket.emit("logout", () => { });
for (const storage of [ localStorage, sessionStorage ]) { this.storage().removeItem("token");
if (storage.getItem("token") === token) {
storage.removeItem("token");
}
}
this.socketIO.token = null; this.socketIO.token = null;
this.loggedIn = false; this.loggedIn = false;
this.username = null; this.username = null;
this.clearData(); this.clearData();
location.reload();
}, },
/** /**
* @returns {void} * @returns {void}
*/ */
clearData() { clearData() {
this.stackListLoaded = false;
}, },
afterLogin() { afterLogin() {

View File

@ -4,19 +4,19 @@
<h1 v-if="isAdd" class="mb-3">{{ $t("compose") }}</h1> <h1 v-if="isAdd" class="mb-3">{{ $t("compose") }}</h1>
<h1 v-else class="mb-3"> <h1 v-else class="mb-3">
<Uptime :stack="globalStack" :pill="true" /> {{ stack.name }} <Uptime :stack="globalStack" :pill="true" /> {{ stack.name }}
<span v-if="$root.agentCount > 1 && endpoint !== ''" class="agent-name"> <span v-if="$root.agentCount > 1" class="agent-name">
({{ endpointDisplay }}) ({{ endpointDisplay }})
</span> </span>
</h1> </h1>
<div v-if="stack.isManagedByDockge" class="mb-3"> <div v-if="stack.isManagedByDockge" class="mb-3">
<div class="btn-group me-2" role="group"> <div class="btn-group me-2" role="group">
<button v-if="isEditMode" class="btn btn-primary" :disabled="processing || hasConfigErrors" @click="deployStack"> <button v-if="isEditMode" class="btn btn-primary" :disabled="processing" @click="deployStack">
<font-awesome-icon icon="rocket" class="me-1" /> <font-awesome-icon icon="rocket" class="me-1" />
{{ $t("deployStack") }} {{ $t("deployStack") }}
</button> </button>
<button v-if="isEditMode" class="btn btn-normal" :disabled="processing || hasConfigErrors || (!isAdd && !dirty)" @click="saveStack"> <button v-if="isEditMode" class="btn btn-normal" :disabled="processing" @click="saveStack">
<font-awesome-icon icon="save" class="me-1" /> <font-awesome-icon icon="save" class="me-1" />
{{ $t("saveStackDraft") }} {{ $t("saveStackDraft") }}
</button> </button>
@ -61,33 +61,10 @@
</button> </button>
</div> </div>
<p v-if="saveError" class="alert alert-danger" role="alert">{{ $t(saveError) }}</p>
<section v-if="!isAdd && !isEditMode && autoUpdate" class="shadow-box mb-3" aria-labelledby="auto-update-heading">
<h2 id="auto-update-heading" class="h6 mb-2">{{ $t("autoUpdateTitle") }}</h2>
<div class="form-check form-switch mb-1">
<input
id="auto-update-toggle" class="form-check-input" type="checkbox" role="switch"
:checked="autoUpdate.enabled" :disabled="processing || autoUpdateSaving"
aria-describedby="auto-update-description" @change="setAutoUpdate"
>
<label for="auto-update-toggle" class="form-check-label">{{ $t("autoUpdateEnable") }}</label>
</div>
<p id="auto-update-description" class="small mb-0">{{ $t("autoUpdateDescription") }}</p>
<p v-if="autoUpdate.lastRun" class="small mt-2 mb-0">
{{ $t("autoUpdateLastRun", {
time: new Date(autoUpdate.lastRun.at).toLocaleString($i18n.locale),
result: $t("autoUpdateResult." + autoUpdate.lastRun.result),
}) }}
</p>
</section>
<ImageVulnerabilities v-if="!isAdd && !isEditMode && imageScanSupported" :stack-name="stack.name" :endpoint="endpoint" />
<!-- URLs --> <!-- URLs -->
<div v-if="urls.length > 0" class="mb-3"> <div v-if="urls.length > 0" class="mb-3">
<a v-for="(urlItem, index) in urls" :key="index" target="_blank" :href="urlItem.url"> <a v-for="(url, index) in urls" :key="index" target="_blank" :href="url.url">
<span class="badge bg-secondary me-2">{{ urlItem.display }}</span> <span class="badge bg-secondary me-2">{{ url.display }}</span>
</a> </a>
</div> </div>
@ -104,7 +81,7 @@
></Terminal> ></Terminal>
</transition> </transition>
<fieldset v-if="stack.isManagedByDockge" class="row" :disabled="processing"> <div v-if="stack.isManagedByDockge" class="row">
<div class="col-lg-6"> <div class="col-lg-6">
<!-- General --> <!-- General -->
<div v-if="isAdd"> <div v-if="isAdd">
@ -121,8 +98,8 @@
<div class="mt-3"> <div class="mt-3">
<label for="name" class="form-label">{{ $t("dockgeAgent") }}</label> <label for="name" class="form-label">{{ $t("dockgeAgent") }}</label>
<select v-model="stack.endpoint" class="form-select"> <select v-model="stack.endpoint" class="form-select">
<option v-for="(agent, agentEndpoint) in $root.agentList" :key="agentEndpoint" :value="agentEndpoint" :disabled="$root.agentStatusList[agentEndpoint] != 'online'"> <option v-for="(agent, endpoint) in $root.agentList" :key="endpoint" :value="endpoint" :disabled="$root.agentStatusList[endpoint] != 'online'">
({{ $root.agentStatusList[agentEndpoint] }}) {{ (agent.name !== '') ? agent.name : agent.url || $t("Current") }} ({{ $root.agentStatusList[endpoint] }}) {{ (endpoint) ? endpoint : $t("currentEndpoint") }}
</option> </option>
</select> </select>
</div> </div>
@ -151,11 +128,8 @@
:name="name" :name="name"
:is-edit-mode="isEditMode" :is-edit-mode="isEditMode"
:first="name === Object.keys(jsonConfig.services)[0]" :first="name === Object.keys(jsonConfig.services)[0]"
:serviceStatus="serviceStatusList[name]" :status="serviceStatusList[name]?.state"
:dockerStats="dockerStats" :ports="serviceStatusList[name]?.ports"
@start-service="startService"
@stop-service="stopService"
@restart-service="restartService"
/> />
</div> </div>
@ -190,13 +164,45 @@
</div> </div>
</div> </div>
<div class="col-lg-6"> <div class="col-lg-6">
<StackConfigEditor <h4 class="mb-3">{{ stack.composeFileName }}</h4>
v-if="!processing || stack.composeYAML !== undefined"
v-model:yaml="stack.composeYAML" v-model:env="stack.composeENV" <!-- YAML editor -->
class="mb-3" :file-name="stack.composeFileName || 'compose.yaml'" <div class="shadow-box mb-3 editor-box" :class="{'edit-mode' : isEditMode}">
:editable="isEditMode" :disabled="processing" :dirty="dirty" <code-mirror
@save="saveStack" ref="editor"
v-model="stack.composeYAML"
:extensions="extensions"
minimal
wrap="true"
dark="true"
tab="true"
:disabled="!isEditMode"
:hasFocus="editorFocus"
@change="yamlCodeChange"
/> />
</div>
<div v-if="isEditMode" class="mb-3">
{{ yamlError }}
</div>
<!-- ENV editor -->
<div v-if="isEditMode">
<h4 class="mb-3">.env</h4>
<div class="shadow-box mb-3 editor-box" :class="{'edit-mode' : isEditMode}">
<code-mirror
ref="editor"
v-model="stack.composeENV"
:extensions="extensionsEnv"
minimal
wrap="true"
dark="true"
tab="true"
:disabled="!isEditMode"
:hasFocus="editorFocus"
@change="yamlCodeChange"
/>
</div>
</div>
<div v-if="isEditMode"> <div v-if="isEditMode">
<!-- Volumes --> <!-- Volumes -->
@ -222,7 +228,7 @@
<prism-editor v-if="false" v-model="yamlConfig" class="yaml-editor" :highlight="highlighter" line-numbers @input="yamlCodeChange"></prism-editor> <prism-editor v-if="false" v-model="yamlConfig" class="yaml-editor" :highlight="highlighter" line-numbers @input="yamlCodeChange"></prism-editor>
</div>--> </div>-->
</div> </div>
</fieldset> </div>
<div v-if="!stack.isManagedByDockge && !processing"> <div v-if="!stack.isManagedByDockge && !processing">
{{ $t("stackNotManagedByDockgeMsg") }} {{ $t("stackNotManagedByDockgeMsg") }}
@ -237,8 +243,11 @@
</template> </template>
<script> <script>
import ImageVulnerabilities from "../components/ImageVulnerabilities.vue"; import CodeMirror from "vue-codemirror6";
import StackConfigEditor from "../components/StackConfigEditor.vue"; import { yaml } from "@codemirror/lang-yaml";
import { python } from "@codemirror/lang-python";
import { dracula as editorTheme } from "thememirror";
import { lineNumbers, EditorView } from "@codemirror/view";
import { parseDocument, Document } from "yaml"; import { parseDocument, Document } from "yaml";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
@ -254,8 +263,7 @@ import {
import { BModal } from "bootstrap-vue-next"; import { BModal } from "bootstrap-vue-next";
import NetworkInput from "../components/NetworkInput.vue"; import NetworkInput from "../components/NetworkInput.vue";
import dotenv from "dotenv"; import dotenv from "dotenv";
import { markRaw } from "vue"; import { ref } from "vue";
import { analyzeEnv } from "../../../common/env-file";
const template = ` const template = `
services: services:
@ -267,15 +275,15 @@ services:
`; `;
const envDefault = "# VARIABLE=value #comment"; const envDefault = "# VARIABLE=value #comment";
let yamlErrorTimeout = null;
let serviceStatusTimeout = null; let serviceStatusTimeout = null;
let dockerStatsTimeout = null;
export default { export default {
components: { components: {
ImageVulnerabilities,
StackConfigEditor,
NetworkInput, NetworkInput,
FontAwesomeIcon, FontAwesomeIcon,
CodeMirror,
BModal, BModal,
}, },
beforeRouteUpdate(to, from, next) { beforeRouteUpdate(to, from, next) {
@ -284,19 +292,39 @@ export default {
beforeRouteLeave(to, from, next) { beforeRouteLeave(to, from, next) {
this.exitConfirm(next); this.exitConfirm(next);
}, },
setup() {
const editorFocus = ref(false);
const focusEffectHandler = (state, focusing) => {
editorFocus.value = focusing;
return null;
};
const extensions = [
editorTheme,
yaml(),
lineNumbers(),
EditorView.focusChangeEffect.of(focusEffectHandler)
];
const extensionsEnv = [
editorTheme,
python(),
lineNumbers(),
EditorView.focusChangeEffect.of(focusEffectHandler)
];
return { extensions,
extensionsEnv,
editorFocus };
},
yamlDoc: null, // For keeping the yaml comments
data() { data() {
return { return {
jsonConfig: {}, jsonConfig: {},
envsubstJSONConfig: {}, envsubstJSONConfig: {},
yamlError: "", yamlError: "",
yamlDoc: null,
updatingFromYaml: false,
savedConfig: null,
saveError: "",
processing: true, processing: true,
autoUpdate: null,
autoUpdateSaving: false,
imageScanSupported: false,
showProgressTerminal: false, showProgressTerminal: false,
progressTerminalRows: PROGRESS_TERMINAL_ROWS, progressTerminalRows: PROGRESS_TERMINAL_ROWS,
combinedTerminalRows: COMBINED_TERMINAL_ROWS, combinedTerminalRows: COMBINED_TERMINAL_ROWS,
@ -305,24 +333,14 @@ export default {
}, },
serviceStatusList: {}, serviceStatusList: {},
dockerStats: {},
isEditMode: false, isEditMode: false,
submitted: false, submitted: false,
showDeleteDialog: false, showDeleteDialog: false,
newContainerName: "", newContainerName: "",
stopServiceStatusTimeout: false, stopServiceStatusTimeout: false,
stopDockerStatsTimeout: false,
}; };
}, },
computed: { computed: {
dirty() {
return this.isEditMode && this.savedConfig !== null
&& (this.stack.composeYAML !== this.savedConfig.yaml || this.stack.composeENV !== this.savedConfig.env
|| this.stack.name !== this.savedConfig.name || this.endpoint !== this.savedConfig.endpoint);
},
hasConfigErrors() {
return Boolean(this.yamlError) || analyzeEnv(this.stack.composeENV || "").some(issue => issue.severity === "error");
},
endpointDisplay() { endpointDisplay() {
return this.$root.endpointDisplayFunction(this.endpoint); return this.$root.endpointDisplayFunction(this.endpoint);
}, },
@ -407,21 +425,28 @@ export default {
watch: { watch: {
"stack.composeYAML": { "stack.composeYAML": {
handler() { handler() {
if (this.editorFocus) {
console.debug("yaml code changed");
this.yamlCodeChange(); this.yamlCodeChange();
}
}, },
deep: true, deep: true,
}, },
"stack.composeENV": { "stack.composeENV": {
handler() { handler() {
this.updateEnvironmentPreview(); if (this.editorFocus) {
console.debug("env code changed");
this.yamlCodeChange();
}
}, },
deep: true, deep: true,
}, },
jsonConfig: { jsonConfig: {
handler() { handler() {
if (!this.updatingFromYaml && !this.yamlError) { if (!this.editorFocus) {
console.debug("jsonConfig changed");
let doc = new Document(this.jsonConfig); let doc = new Document(this.jsonConfig);
@ -431,11 +456,10 @@ export default {
} }
this.stack.composeYAML = doc.toString(); this.stack.composeYAML = doc.toString();
this.yamlDoc = markRaw(doc); this.yamlDoc = doc;
} }
}, },
deep: true, deep: true,
flush: "sync",
}, },
$route(to, from) { $route(to, from) {
@ -443,7 +467,6 @@ export default {
} }
}, },
mounted() { mounted() {
window.addEventListener("beforeunload", this.confirmPageExit);
if (this.isAdd) { if (this.isAdd) {
this.processing = false; this.processing = false;
this.isEditMode = true; this.isEditMode = true;
@ -474,7 +497,6 @@ export default {
}; };
this.yamlCodeChange(); this.yamlCodeChange();
this.captureSavedConfig();
} else { } else {
this.stack.name = this.$route.params.stackName; this.stack.name = this.$route.params.stackName;
@ -482,11 +504,9 @@ export default {
} }
this.requestServiceStatus(); this.requestServiceStatus();
this.requestDockerStats();
}, },
unmounted() { unmounted() {
window.removeEventListener("beforeunload", this.confirmPageExit);
this.exitAction();
}, },
methods: { methods: {
startServiceStatusTimeout() { startServiceStatusTimeout() {
@ -496,13 +516,6 @@ export default {
}, 5000); }, 5000);
}, },
startDockerStatsTimeout() {
clearTimeout(dockerStatsTimeout);
dockerStatsTimeout = setTimeout(async () => {
this.requestDockerStats();
}, 5000);
},
requestServiceStatus() { requestServiceStatus() {
// Do not request if it is add mode // Do not request if it is add mode
if (this.isAdd) { if (this.isAdd) {
@ -519,19 +532,8 @@ export default {
}); });
}, },
requestDockerStats() {
this.$root.emitAgent(this.endpoint, "dockerStats", (res) => {
if (res.ok) {
this.dockerStats = res.dockerStats;
}
if (!this.stopDockerStatsTimeout) {
this.startDockerStatsTimeout();
}
});
},
exitConfirm(next) { exitConfirm(next) {
if (this.dirty) { if (this.isEditMode) {
if (confirm(this.$t("confirmLeaveStack"))) { if (confirm(this.$t("confirmLeaveStack"))) {
this.exitAction(); this.exitAction();
next(); next();
@ -545,14 +547,9 @@ export default {
}, },
exitAction() { exitAction() {
if (this.stopServiceStatusTimeout && this.stopDockerStatsTimeout) {
return;
}
console.log("exitAction"); console.log("exitAction");
this.stopServiceStatusTimeout = true; this.stopServiceStatusTimeout = true;
this.stopDockerStatsTimeout = true;
clearTimeout(serviceStatusTimeout); clearTimeout(serviceStatusTimeout);
clearTimeout(dockerStatsTimeout);
// Leave Combined Terminal // Leave Combined Terminal
console.debug("leaveCombinedTerminal", this.endpoint, this.stack.name); console.debug("leaveCombinedTerminal", this.endpoint, this.stack.name);
@ -568,52 +565,19 @@ export default {
this.$root.emitAgent(this.endpoint, "getStack", this.stack.name, (res) => { this.$root.emitAgent(this.endpoint, "getStack", this.stack.name, (res) => {
if (res.ok) { if (res.ok) {
this.stack = res.stack; this.stack = res.stack;
this.autoUpdate = res.autoUpdate ?? null;
this.imageScanSupported = res.imageScanSupported === true;
this.yamlCodeChange(); this.yamlCodeChange();
this.captureSavedConfig();
this.saveError = "";
this.processing = false; this.processing = false;
this.bindTerminal(); this.bindTerminal();
} else { } else {
this.$root.toastRes(res); this.$root.toastRes(res);
this.processing = false;
} }
}); });
}, },
/**
* Save the update policy on the host that runs this stack.
* @param {Event} event Change event from the update switch
* @returns {Promise<void>}
*/
async setAutoUpdate(event) {
const input = event.target;
this.autoUpdateSaving = true;
try {
const res = await this.$root.getSocket().timeout(15000).emitWithAck(
"agent", this.endpoint, "setStackAutoUpdate", this.stack.name, input.checked
);
if (res.ok) {
this.autoUpdate = res.autoUpdate;
} else {
this.$root.toastRes(res);
}
} catch {
this.$root.toastError("autoUpdateSaveFailed");
} finally {
input.checked = this.autoUpdate.enabled;
this.autoUpdateSaving = false;
}
},
deployStack() { deployStack() {
if (this.hasConfigErrors) {
return;
}
this.processing = true; this.processing = true;
if (!this.jsonConfig.services || Object.keys(this.jsonConfig.services).length === 0) { if (!this.jsonConfig.services) {
this.$root.toastError("No services found in compose.yaml"); this.$root.toastError("No services found in compose.yaml");
this.processing = false; this.processing = false;
return; return;
@ -642,61 +606,29 @@ export default {
this.bindTerminal(); this.bindTerminal();
const args = [ this.stack.name, this.stack.composeYAML, this.stack.composeENV, this.isAdd ]; this.$root.emitAgent(this.stack.endpoint, "deployStack", this.stack.name, this.stack.composeYAML, this.stack.composeENV, this.isAdd, (res) => {
if (this.stack.revision) {
args.push(this.stack.revision);
}
this.saveError = "";
this.$root.emitAgent(this.endpoint, "deployStack", ...args, (res) => {
this.processing = false; this.processing = false;
this.$root.toastRes(res); this.$root.toastRes(res);
if (res.ok) { if (res.ok) {
this.isEditMode = false; this.isEditMode = false;
this.captureSavedConfig();
this.$router.push(this.url); this.$router.push(this.url);
} else {
this.saveError = res.msg || "editorSaveFailed";
} }
}); });
}, },
async saveStack() { saveStack() {
if (!this.isEditMode || this.processing || this.hasConfigErrors || (!this.isAdd && !this.dirty)) {
return;
}
this.processing = true; this.processing = true;
this.saveError = "";
const isAdd = this.isAdd; this.$root.emitAgent(this.stack.endpoint, "saveStack", this.stack.name, this.stack.composeYAML, this.stack.composeENV, this.isAdd, (res) => {
const submitted = {
yaml: this.stack.composeYAML,
env: this.stack.composeENV,
name: this.stack.name,
endpoint: this.endpoint,
};
const savedURL = this.url;
const args = [ this.stack.name, this.stack.composeYAML, this.stack.composeENV, isAdd ];
if (this.stack.revision) {
args.push(this.stack.revision);
}
try {
const res = await this.$root.getSocket().timeout(15000).emitWithAck("agent", this.endpoint, "saveStack", ...args);
if (res.ok) {
this.stack.revision = res.revision ?? this.stack.revision;
this.savedConfig = submitted;
this.$root.toastRes(res);
if (isAdd) {
this.isEditMode = false;
this.$router.push(savedURL);
}
} else {
this.saveError = res.msg || "editorSaveFailed";
}
} catch {
this.saveError = "editorSaveUnconfirmed";
} finally {
this.processing = false; this.processing = false;
this.$root.toastRes(res);
if (res.ok) {
this.isEditMode = false;
this.$router.push(this.url);
} }
});
}, },
startStack() { startStack() {
@ -754,9 +686,6 @@ export default {
}, },
discardStack() { discardStack() {
if (this.dirty && !confirm(this.$t("confirmLeaveStack"))) {
return;
}
this.loadStack(); this.loadStack();
this.isEditMode = false; this.isEditMode = false;
}, },
@ -768,9 +697,6 @@ export default {
} }
const config = doc.toJS() ?? {}; const config = doc.toJS() ?? {};
if (typeof config !== "object" || Array.isArray(config)) {
throw new Error(this.$t("editorYamlMapping"));
}
// Check data types // Check data types
// "services" must be an object // "services" must be an object
@ -792,47 +718,26 @@ export default {
try { try {
let { config, doc } = this.yamlToJSON(this.stack.composeYAML); let { config, doc } = this.yamlToJSON(this.stack.composeYAML);
this.updatingFromYaml = true; this.yamlDoc = doc;
this.yamlDoc = markRaw(doc);
this.yamlError = "";
this.jsonConfig = config; this.jsonConfig = config;
this.updateEnvironmentPreview();
} catch (e) {
this.yamlError = e.message;
} finally {
this.updatingFromYaml = false;
}
},
/** Refresh interpolation without rewriting either source file. */ let env = dotenv.parse(this.stack.composeENV);
updateEnvironmentPreview() { let envYAML = envsubstYAML(this.stack.composeYAML, env);
if (this.yamlError || this.stack.composeYAML === undefined) {
return;
}
try {
const env = dotenv.parse(this.stack.composeENV || "");
const envYAML = envsubstYAML(this.stack.composeYAML, env);
this.envsubstJSONConfig = this.yamlToJSON(envYAML).config; this.envsubstJSONConfig = this.yamlToJSON(envYAML).config;
} catch {
this.envsubstJSONConfig = {}; clearTimeout(yamlErrorTimeout);
this.yamlError = "";
} catch (e) {
clearTimeout(yamlErrorTimeout);
if (this.yamlError) {
this.yamlError = e.message;
} else {
yamlErrorTimeout = setTimeout(() => {
this.yamlError = e.message;
}, 3000);
} }
},
/** Remember the content confirmed by the server for dirty tracking. */
captureSavedConfig() {
this.savedConfig = {
yaml: this.stack.composeYAML,
env: this.stack.composeENV,
name: this.stack.name,
endpoint: this.endpoint,
};
},
/** Ask the browser before reloading or closing a dirty editor. */
confirmPageExit(event) {
if (this.dirty) {
event.preventDefault();
event.returnValue = "";
} }
}, },
@ -841,13 +746,11 @@ export default {
}, },
checkYAML() { checkYAML() {
return !this.hasConfigErrors;
}, },
addContainer() { addContainer() {
if (!this.checkYAML()) { this.checkYAML();
return;
}
if (this.jsonConfig.services[this.newContainerName]) { if (this.jsonConfig.services[this.newContainerName]) {
this.$root.toastError("Container name already exists"); this.$root.toastError("Container name already exists");
@ -874,44 +777,6 @@ export default {
this.stack.name = this.stack?.name?.toLowerCase(); this.stack.name = this.stack?.name?.toLowerCase();
}, },
startService(serviceName) {
this.processing = true;
this.$root.emitAgent(this.endpoint, "startService", this.stack.name, serviceName, (res) => {
this.processing = false;
this.$root.toastRes(res);
if (res.ok) {
this.requestServiceStatus(); // Refresh service status
}
});
},
stopService(serviceName) {
this.processing = true;
this.$root.emitAgent(this.endpoint, "stopService", this.stack.name, serviceName, (res) => {
this.processing = false;
this.$root.toastRes(res);
if (res.ok) {
this.requestServiceStatus(); // Refresh service status
}
});
},
restartService(serviceName) {
this.processing = true;
this.$root.emitAgent(this.endpoint, "restartService", this.stack.name, serviceName, (res) => {
this.processing = false;
this.$root.toastRes(res);
if (res.ok) {
this.requestServiceStatus(); // Refresh service status
}
});
},
} }
}; };
</script> </script>

View File

@ -7,22 +7,9 @@
<div v-else class="alert alert-warning shadow-box" role="alert"> <div v-else class="alert alert-warning shadow-box" role="alert">
<h4 class="alert-heading">{{ $t("Console is not enabled") }}</h4> <h4 class="alert-heading">{{ $t("Console is not enabled") }}</h4>
<i18n-t keypath="ConsoleNotEnabledMSG1" tag="p"> <p v-html="$t('ConsoleNotEnabledMSG1')"></p>
<template #docker><code>{{ $t('dockerCode') }}</code></template> <p v-html="$t('ConsoleNotEnabledMSG2')"></p>
<template #rm><code>{{ $t('rmCode') }}</code></template> <p v-html="$t('ConsoleNotEnabledMSG3')"></p>
</i18n-t>
<i18n-t keypath="ConsoleNotEnabledMSG2" tag="p">
<template #rmRf>
<code>{{ $t('rmRfCode') }}</code>
</template>
</i18n-t>
<i18n-t keypath="ConsoleNotEnabledMSG3" tag="p">
<template #envVar>
<code>{{ $t('envVarCode') }}</code>
</template>
</i18n-t>
</div> </div>
</div> </div>
</transition> </transition>

View File

@ -1,32 +1,11 @@
<template> <template>
<div class="container-fluid"> <div class="container-fluid">
<div class="row"> <div class="row">
<div v-if="desktop" class="col-md-4 col-xl-3"> <div v-if="!$root.isMobile" class="col-12 col-md-4 col-xl-3">
<StackList class="stack-navigation stack-nav-sidebar" /> <div>
<router-link to="/compose" class="btn btn-primary mb-3"><font-awesome-icon icon="plus" /> {{ $t("compose") }}</router-link>
</div> </div>
<div v-else class="col-12 mb-3 stack-navigation"> <StackList :scrollbar="true" />
<DialogRoot v-model:open="stackListOpen" lazy-mount>
<DialogTrigger type="button" class="stack-nav-button">
<font-awesome-icon icon="list" aria-hidden="true" /> {{ $t("stackListTitle") }}
</DialogTrigger>
<Teleport to="body">
<DialogBackdrop class="stack-nav-backdrop" />
<DialogPositioner class="stack-nav-positioner">
<DialogContent class="stack-navigation stack-nav-drawer">
<StackList @navigate="stackListOpen = false">
<template #title>
<DialogTitle class="stack-nav-title">{{ $t("stackListTitle") }}</DialogTitle>
</template>
<template #close>
<DialogCloseTrigger type="button" class="stack-nav-button stack-nav-close" :aria-label="$t('stackListClose')">
<font-awesome-icon icon="times" aria-hidden="true" />
</DialogCloseTrigger>
</template>
</StackList>
</DialogContent>
</DialogPositioner>
</Teleport>
</DialogRoot>
</div> </div>
<div ref="container" class="col-12 col-md-8 col-xl-9 mb-3"> <div ref="container" class="col-12 col-md-8 col-xl-9 mb-3">
@ -38,52 +17,20 @@
</template> </template>
<script> <script>
import { DialogBackdrop, DialogCloseTrigger, DialogContent, DialogPositioner, DialogRoot, DialogTitle, DialogTrigger } from "@ark-ui/vue/dialog";
import StackList from "../components/StackList.vue";
import "../styles/stack-navigation.css";
const desktopViewport = window.matchMedia("(min-width: 768px)"); import StackList from "../components/StackList.vue";
export default { export default {
components: { components: {
DialogBackdrop,
DialogCloseTrigger,
DialogContent,
DialogPositioner,
DialogRoot,
DialogTitle,
DialogTrigger,
StackList, StackList,
}, },
data() { data() {
return { return {
height: 0, height: 0
desktop: desktopViewport.matches,
stackListOpen: false,
}; };
}, },
watch: {
"$route.fullPath"() {
this.stackListOpen = false;
},
},
mounted() { mounted() {
this.height = this.$refs.container.offsetHeight; this.height = this.$refs.container.offsetHeight;
desktopViewport.addEventListener("change", this.updateViewport);
},
beforeUnmount() {
desktopViewport.removeEventListener("change", this.updateViewport);
},
methods: {
/**
* Switch navigation layouts at Bootstrap's medium breakpoint.
* @param {MediaQueryListEvent} event The viewport match state
* @returns {void}
*/
updateViewport(event) {
this.stackListOpen = false;
this.desktop = event.matches;
},
}, },
}; };
</script> </script>

View File

@ -40,7 +40,7 @@
<div class="shadow-box big-padding"> <div class="shadow-box big-padding">
<h4 class="mb-3">{{ $tc("dockgeAgent", 2) }} <span class="badge bg-warning" style="font-size: 12px;">beta</span></h4> <h4 class="mb-3">{{ $tc("dockgeAgent", 2) }} <span class="badge bg-warning" style="font-size: 12px;">beta</span></h4>
<div v-for="(agentItem, endpoint) in $root.agentList" :key="endpoint" class="mb-3 agent"> <div v-for="(agent, endpoint) in $root.agentList" :key="endpoint" class="mb-3 agent">
<!-- Agent Status --> <!-- Agent Status -->
<template v-if="$root.agentStatusList[endpoint]"> <template v-if="$root.agentStatusList[endpoint]">
<span v-if="$root.agentStatusList[endpoint] === 'online'" class="badge bg-primary me-2">{{ $t("agentOnline") }}</span> <span v-if="$root.agentStatusList[endpoint] === 'online'" class="badge bg-primary me-2">{{ $t("agentOnline") }}</span>
@ -49,27 +49,15 @@
</template> </template>
<!-- Agent Display Name --> <!-- Agent Display Name -->
<template v-if="$root.agentStatusList[endpoint]"> <span v-if="endpoint === ''">{{ $t("currentEndpoint") }}</span>
<span v-if="endpoint === '' && agentItem.name === ''" class="badge bg-secondary me-2">Current</span> <a v-else :href="agent.url" target="_blank">{{ endpoint }}</a>
<span v-else-if="agentItem.name === ''" :href="agentItem.url" class="me-2">{{ endpoint }}</span>
<span v-else :href="agentItem.url" class="me-2">{{ agentItem.name }}</span>
</template>
<!-- Edit Name -->
<font-awesome-icon v-if="agentItem.name !== ''" icon="pen-to-square" @click="showEditAgentNameDialog[agentItem.name] = !showEditAgentNameDialog[agentItem.Name]" />
<!-- Edit Dialog -->
<BModal v-model="showEditAgentNameDialog[agentItem.name]" :no-close-on-backdrop="true" :close-on-esc="true" :okTitle="$t('Update Name')" okVariant="info" @ok="updateName(agentItem.url, agentItem.updatedName)">
<label for="Update Name" class="form-label">Current value: {{ $t(agentItem.name) }}</label>
<input id="updatedName" v-model="agentItem.updatedName" type="text" class="form-control" optional>
</BModal>
<!-- Remove Button --> <!-- Remove Button -->
<font-awesome-icon v-if="endpoint !== ''" class="ms-2 remove-agent" icon="trash" @click="showRemoveAgentDialog[agentItem.url] = !showRemoveAgentDialog[agentItem.url]" /> <font-awesome-icon v-if="endpoint !== ''" class="ms-2 remove-agent" icon="trash" @click="showRemoveAgentDialog[agent.url] = !showRemoveAgentDialog[agent.url]" />
<!-- Remove Agent Dialog --> <!-- Remoe Agent Dialog -->
<BModal v-model="showRemoveAgentDialog[agentItem.url]" :okTitle="$t('removeAgent')" okVariant="danger" @ok="removeAgent(agentItem.url)"> <BModal v-model="showRemoveAgentDialog[agent.url]" :okTitle="$t('removeAgent')" okVariant="danger" @ok="removeAgent(agent.url)">
<p>{{ agentItem.url }}</p> <p>{{ agent.url }}</p>
{{ $t("removeAgentMsg") }} {{ $t("removeAgentMsg") }}
</BModal> </BModal>
</div> </div>
@ -93,11 +81,6 @@
<input id="password" v-model="agent.password" type="password" class="form-control" required autocomplete="new-password"> <input id="password" v-model="agent.password" type="password" class="form-control" required autocomplete="new-password">
</div> </div>
<div class="mb-3">
<label for="name" class="form-label">{{ $t("Friendly Name") }}</label>
<input id="name" v-model="agent.name" type="text" class="form-control" optional>
</div>
<button type="submit" class="btn btn-primary" :disabled="connectingAgent"> <button type="submit" class="btn btn-primary" :disabled="connectingAgent">
<template v-if="connectingAgent">{{ $t("connecting") }}</template> <template v-if="connectingAgent">{{ $t("connecting") }}</template>
<template v-else>{{ $t("connect") }}</template> <template v-else>{{ $t("connect") }}</template>
@ -138,14 +121,11 @@ export default {
dockerRunCommand: "", dockerRunCommand: "",
showAgentForm: false, showAgentForm: false,
showRemoveAgentDialog: {}, showRemoveAgentDialog: {},
showEditAgentNameDialog: {},
connectingAgent: false, connectingAgent: false,
agent: { agent: {
url: "http://", url: "http://",
username: "", username: "",
password: "", password: "",
name: "",
updatedName: "",
} }
}; };
}, },
@ -219,19 +199,6 @@ export default {
}); });
}, },
updateName(url, updatedName) {
this.$root.getSocket().emit("updateAgent", url, updatedName, (res) => {
this.$root.toastRes(res);
if (res.ok) {
this.showAgentForm = false;
this.agent = {
updatedName: "",
};
}
});
},
getStatusNum(statusName) { getStatusNum(statusName) {
let num = 0; let num = 0;
@ -319,7 +286,7 @@ export default {
} }
}, },
} },
}; };
</script> </script>

View File

@ -137,21 +137,15 @@ export default {
* Save Settings * Save Settings
* @param {saveSettingsCB} [callback] * @param {saveSettingsCB} [callback]
* @param {string} [currentPassword] Only need for disableAuth to true * @param {string} [currentPassword] Only need for disableAuth to true
* @param {boolean} [disableAuth] New value when explicitly changing authentication
*/ */
saveSettings(callback, currentPassword, disableAuth) { saveSettings(callback, currentPassword) {
let valid = this.validateSettings(); let valid = this.validateSettings();
if (valid.success) { if (valid.success) {
const data = { ...this.settings }; this.$root.getSocket().emit("setSettings", this.settings, currentPassword, (res) => {
delete data.disableAuth;
if (disableAuth !== undefined) {
data.disableAuth = disableAuth;
}
this.$root.getSocket().emit("setSettings", data, currentPassword, (res) => {
this.$root.toastRes(res); this.$root.toastRes(res);
this.loadSettings(); this.loadSettings();
if (res.ok && callback) { if (callback) {
callback(); callback();
} }
}); });

View File

@ -382,6 +382,18 @@ optgroup {
color: $dark-font-color; color: $dark-font-color;
} }
.stack-list {
.item {
&:hover {
background-color: $dark-bg2;
}
&.active {
background-color: $dark-bg2;
}
}
}
@media (max-width: 550px) { @media (max-width: 550px) {
.table-shadow-box { .table-shadow-box {
tbody { tbody {
@ -466,6 +478,46 @@ optgroup {
opacity: 0; opacity: 0;
} }
.stack-list {
&.scrollbar {
overflow-y: auto;
}
@media (max-width: 770px) {
&.scrollbar {
height: calc(100% - 97px);
}
}
.item {
display: flex;
align-items: center;
height: 52px;
text-decoration: none;
border-radius: 10px;
transition: all ease-in-out 0.15s;
width: 100%;
padding: 0 8px;
&.disabled {
opacity: 0.3;
}
&:hover {
background-color: $highlight-white;
}
&.active {
background-color: #cdf8f4;
}
.title {
display: inline-block;
margin-top: -4px;
}
}
}
.alert-success { .alert-success {
color: #122f21; color: #122f21;
background-color: $primary; background-color: $primary;

View File

@ -1,318 +0,0 @@
@layer reset, base, tokens, recipes, utilities;
.stack-nav-panel {
display: flex;
flex-direction: column;
min-height: 0;
color: var(--stack-nav-colors-text);
background: var(--stack-nav-colors-surface);
}
.stack-nav-sidebar {
position: sticky;
top: 1rem;
max-height: calc(100dvh - 2rem);
border: 1px solid var(--stack-nav-colors-border);
border-radius: 0.875rem;
overflow: hidden;
}
.stack-nav-header,
.stack-nav-summary {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.75rem 1rem;
}
.stack-nav-title {
flex: 1;
margin: 0;
font-size: 1.125rem;
font-weight: 650;
}
.stack-nav-button,
.stack-nav-field input,
.stack-nav-field select {
min-height: 2.5rem;
border: 1px solid var(--stack-nav-colors-border);
border-radius: 0.5rem;
color: var(--stack-nav-colors-text);
background: var(--stack-nav-colors-surface);
font-size: 0.875rem;
}
.stack-nav-button {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.375rem;
padding: 0.375rem 0.625rem;
text-decoration: none;
font-weight: 600;
}
.stack-nav-button:hover {
color: var(--stack-nav-colors-text);
background: var(--stack-nav-colors-subtle);
}
.stack-nav-primary,
.stack-nav-primary:hover {
border-color: transparent;
color: var(--stack-nav-colors-accent-text);
background: var(--stack-nav-colors-accent);
}
.stack-nav-primary:hover {
opacity: 0.9;
}
.stack-navigation :is(a, button, input, select):focus-visible {
outline: 2px solid var(--stack-nav-colors-accent);
outline-offset: 2px;
}
.stack-nav-controls {
display: grid;
gap: 0.75rem;
padding: 0 1rem;
}
.stack-nav-filters {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.5rem;
}
.stack-nav-field {
display: grid;
gap: 0.25rem;
min-width: 0;
color: var(--stack-nav-colors-muted);
font-size: 0.75rem;
font-weight: 600;
}
.stack-nav-field :is(input, select) {
width: 100%;
padding: 0.375rem 0.5rem;
font-weight: 400;
}
.stack-nav-field input::placeholder {
color: var(--stack-nav-colors-muted);
}
.dark .stack-nav-field :is(input, select) {
color-scheme: dark;
}
.stack-nav-search {
position: relative;
}
.stack-nav-search svg {
position: absolute;
inset-inline-start: 0.625rem;
top: 50%;
transform: translateY(-50%);
pointer-events: none;
}
.stack-nav-search input {
padding-inline-start: 1.875rem;
}
.stack-nav-summary {
justify-content: space-between;
min-height: 2.75rem;
padding-block: 0.25rem;
color: var(--stack-nav-colors-muted);
font-size: 0.75rem;
}
.stack-nav-reset {
min-height: 2rem;
padding: 0;
border: 0;
border-radius: 0.25rem;
color: var(--stack-nav-colors-accent);
background: transparent;
text-decoration: underline;
}
.stack-nav-results {
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
border-top: 1px solid var(--stack-nav-colors-border);
padding: 0.5rem;
}
.stack-nav-group + .stack-nav-group {
margin-top: 0.5rem;
}
.stack-nav-group-heading {
display: flex;
align-items: center;
gap: 0.375rem;
width: 100%;
min-height: 2.5rem;
padding: 0.375rem 0.5rem;
border: 0;
border-radius: 0.5rem;
color: var(--stack-nav-colors-muted);
background: var(--stack-nav-colors-subtle);
text-align: start;
font-size: 0.8125rem;
font-weight: 650;
}
.stack-nav-agent {
flex: 1;
overflow-wrap: anywhere;
}
.stack-nav-group-heading[data-state="closed"] .stack-nav-chevron {
transform: rotate(-90deg);
}
.stack-nav-items {
margin: 0.25rem 0 0;
padding: 0;
list-style: none;
}
.stack-nav-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
min-height: 3.25rem;
padding: 0.375rem 0.5rem;
border-radius: 0.5rem;
color: var(--stack-nav-colors-text);
text-decoration: none;
}
.stack-nav-item:hover {
color: var(--stack-nav-colors-text);
background: var(--stack-nav-colors-subtle);
}
.stack-nav-item[aria-current="page"] {
color: var(--stack-nav-colors-accent);
background: var(--stack-nav-colors-accent-subtle);
}
.stack-nav-item-copy {
display: grid;
min-width: 0;
overflow-wrap: anywhere;
}
.stack-nav-name {
font-size: 0.875rem;
font-weight: 600;
}
.stack-nav-item-meta {
color: var(--stack-nav-colors-muted);
font-size: 0.75rem;
}
.stack-nav-badge,
.stack-nav-connection {
display: inline-flex;
align-items: center;
gap: 0.25rem;
flex-shrink: 0;
padding: 0.125rem 0.375rem;
border-radius: 1rem;
color: var(--stack-nav-colors-muted);
background: var(--stack-nav-colors-subtle);
font-size: 0.75rem;
font-weight: 600;
}
.stack-nav-badge::before,
.stack-nav-connection::before {
width: 0.375rem;
height: 0.375rem;
border-radius: 50%;
background: currentColor;
content: "";
}
.stack-nav-badge[data-state="active"] {
color: var(--stack-nav-colors-accent);
background: var(--stack-nav-colors-accent-subtle);
}
.stack-nav-badge[data-state="exited"],
.stack-nav-connection[data-state="offline"] {
color: var(--stack-nav-colors-danger);
background: var(--stack-nav-colors-danger-subtle);
}
.stack-nav-message {
margin: 0.5rem;
color: var(--stack-nav-colors-muted);
font-size: 0.875rem;
}
.stack-nav-message p {
margin-bottom: 0.25rem;
}
.stack-nav-message a {
color: var(--stack-nav-colors-accent);
}
.stack-nav-backdrop,
.stack-nav-positioner {
position: fixed;
inset: 0;
}
.stack-nav-backdrop {
z-index: 1055;
background: rgb(10 17 24 / 62%);
}
.stack-nav-positioner {
z-index: 1056;
display: flex;
align-items: flex-end;
justify-content: center;
pointer-events: none;
}
.stack-nav-drawer {
display: flex;
width: min(100%, 36rem);
max-height: 88dvh;
padding-bottom: env(safe-area-inset-bottom);
overflow: hidden;
border: 1px solid var(--stack-nav-colors-border);
border-radius: 1rem 1rem 0 0;
outline: none;
background: var(--stack-nav-colors-surface);
pointer-events: auto;
}
.stack-nav-drawer .stack-nav-panel {
width: 100%;
}
.stack-nav-positioner[hidden],
.stack-nav-drawer[hidden] {
display: none;
}
.stack-nav-close {
min-width: 2.5rem;
}

View File

@ -3,7 +3,6 @@ import vue from "@vitejs/plugin-vue";
import Components from "unplugin-vue-components/vite"; import Components from "unplugin-vue-components/vite";
import { BootstrapVueNextResolver } from "unplugin-vue-components/resolvers"; import { BootstrapVueNextResolver } from "unplugin-vue-components/resolvers";
import viteCompression from "vite-plugin-compression"; import viteCompression from "vite-plugin-compression";
import panda from "@pandacss/dev/postcss";
import "vue"; import "vue";
const viteCompressionFilter = /\.(js|mjs|json|css|html|svg)$/i; const viteCompressionFilter = /\.(js|mjs|json|css|html|svg)$/i;
@ -17,11 +16,6 @@ export default defineConfig({
"FRONTEND_VERSION": JSON.stringify(process.env.npm_package_version), "FRONTEND_VERSION": JSON.stringify(process.env.npm_package_version),
}, },
root: "./frontend", root: "./frontend",
css: {
postcss: {
plugins: [ panda({ codegen: false }) ],
},
},
build: { build: {
outDir: "../frontend-dist", outDir: "../frontend-dist",
}, },

2939
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -59,20 +59,13 @@
}, },
"devDependencies": { "devDependencies": {
"@actions/github": "^6.0.0", "@actions/github": "^6.0.0",
"@ark-ui/vue": "~5.40.0",
"@codemirror/commands": "6.10.1",
"@codemirror/lang-python": "^6.1.7", "@codemirror/lang-python": "^6.1.7",
"@codemirror/lang-yaml": "^6.1.2", "@codemirror/lang-yaml": "^6.1.2",
"@codemirror/language": "6.12.1",
"@codemirror/lint": "6.9.2",
"@codemirror/search": "6.5.11",
"@codemirror/view": "6.39.6",
"@fontsource/jetbrains-mono": "^5.2.5", "@fontsource/jetbrains-mono": "^5.2.5",
"@fortawesome/fontawesome-svg-core": "6.4.2", "@fortawesome/fontawesome-svg-core": "6.4.2",
"@fortawesome/free-regular-svg-icons": "6.4.2", "@fortawesome/free-regular-svg-icons": "6.4.2",
"@fortawesome/free-solid-svg-icons": "6.4.2", "@fortawesome/free-solid-svg-icons": "6.4.2",
"@fortawesome/vue-fontawesome": "3.0.3", "@fortawesome/vue-fontawesome": "3.0.3",
"@pandacss/dev": "~2.5.0",
"@types/bcryptjs": "^2.4.6", "@types/bcryptjs": "^2.4.6",
"@types/bootstrap": "~5.2.10", "@types/bootstrap": "~5.2.10",
"@types/command-exists": "~1.2.3", "@types/command-exists": "~1.2.3",

View File

@ -1,38 +0,0 @@
import { defineConfig } from "@pandacss/dev";
export default defineConfig({
presets: [],
preflight: false,
include: [],
cssVarRoot: ":where(.stack-navigation, .stack-config-editor)",
conditions: {
dark: ".dark :where(.stack-navigation, .stack-config-editor) &",
},
theme: {
semanticTokens: {
colors: {
surface: { value: { base: "#ffffff",
_dark: "#161b22" } },
subtle: { value: { base: "#f5f7f8",
_dark: "#1f2730" } },
border: { value: { base: "#d7dee4",
_dark: "#3a4756" } },
text: { value: { base: "#1d2730",
_dark: "#eef3f7" } },
muted: { value: { base: "#536270",
_dark: "#a7b5c3" } },
accent: { value: { base: "#14623b",
_dark: "#8be7af" } },
accentText: { value: { base: "#ffffff",
_dark: "#102b1c" } },
accentSubtle: { value: { base: "#e8f6ed",
_dark: "#213b30" } },
danger: { value: { base: "#9f2929",
_dark: "#ffaeae" } },
dangerSubtle: { value: { base: "#fff0f0",
_dark: "#422a30" } },
},
},
},
prefix: "stack-nav",
});