Compare commits

...

10 Commits

Author SHA1 Message Date
720eade8b5 Improve stack UI, session security, updates, scans and config editor
Some checks failed
Node.js CI - Dockge / ${{ matrix.os }} (22, ubuntu-latest) (push) Successful in 1m47s
json-yaml-validate / json-yaml-validate (push) Successful in 12s
Nightly Release / release-nightly (push) Failing after 44s
Node.js CI - Dockge / ${{ matrix.os }} (22, macos-latest) (push) Has been cancelled
Node.js CI - Dockge / ${{ matrix.os }} (22, windows-latest) (push) Has been cancelled
2026-11-10 23:48:30 +01:00
Louis Lam
0329dabb50
ci: drop the self-hosted ARM runners (#1010) 2026-10-23 14:35:34 +08:00
cmcooper1980
f809ae192b fixed missed v-html xss warning vulnerability 2026-04-18 19:12:17 -05:00
cmcooper1980
749e2c5c88 npm audit fixes, eslint fixes, console warning v-html directive xss vulnerabilty warning fix, and code optimizations 2026-04-18 17:45:38 -05:00
Justin Wiebe
b02f5e092e
Add resource usage stats to the compose page (#700)
Co-authored-by: cmcooper1980 <31871143+cmcooper1980@users.noreply.github.com>
2026-04-11 23:42:38 -05:00
Lance Cain
078f762631
Container control buttons (#649)
Co-authored-by: cmcooper1980 <31871143+cmcooper1980@users.noreply.github.com>
additional QOL commits by @Dracrius
2026-04-11 18:58:45 -05:00
Julian
e589d4ec7e
feat: dockge set/update agent friendly name (#414)
Co-authored-by: cmcooper1980 <31871143+cmcooper1980@users.noreply.github.com>
2026-04-11 14:46:45 -05:00
Matthew McConnell
7e324d9015
Improved stack list ui when using agents (#800) 2026-04-11 14:27:16 -05:00
cmcooper1980
72a941712d
Fix formatting and capitalization in README.md
Corrected formatting and capitalization in README.
2026-04-10 17:21:23 -05:00
Richy HBM
46ce4228a5
Allow specifying which user the stack files should belong to (#83)
Co-authored-by: cmcooper1980 <31871143+cmcooper1980@users.noreply.github.com>
2026-04-10 17:14:18 -05:00
47 changed files with 6610 additions and 1269 deletions

View File

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

View File

@ -81,9 +81,52 @@ curl "https://dockge.kuma.pet/compose.yaml?port=5001&stacksPath=/opt/stacks" --o
- port=`5001`
- 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:
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
```bash

View File

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

View File

@ -8,10 +8,27 @@ export class DockerSocketHandler extends AgentSocketHandler {
create(socket : DockgeSocket, server : DockgeServer, agentSocket : AgentSocket) {
// Do not call super.create()
agentSocket.on("deployStack", async (name : unknown, composeYAML : unknown, composeENV : unknown, isAdd : unknown, callback) => {
const onStackMutation = (event: string, handler: (...args: unknown[]) => Promise<void>) => {
agentSocket.on(event, async (...args: unknown[]) => {
try {
checkLogin(socket);
const name = args[0];
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 {
checkLogin(socket);
const stack = await this.saveStack(server, name, composeYAML, composeENV, isAdd);
const stack = await this.saveStack(server, name, composeYAML, composeENV, isAdd, revision);
await stack.deploy(socket);
server.sendStackList();
callbackResult({
@ -25,14 +42,16 @@ export class DockerSocketHandler extends AgentSocketHandler {
}
});
agentSocket.on("saveStack", async (name : unknown, composeYAML : unknown, composeENV : unknown, isAdd : unknown, callback) => {
onStackMutation("saveStack", 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 {
checkLogin(socket);
await this.saveStack(server, name, composeYAML, composeENV, isAdd);
const stack = await this.saveStack(server, name, composeYAML, composeENV, isAdd, revision);
callbackResult({
ok: true,
msg: "Saved",
msgi18n: true,
revision: stack.revision,
}, callback);
server.sendStackList();
} catch (e) {
@ -40,9 +59,8 @@ export class DockerSocketHandler extends AgentSocketHandler {
}
});
agentSocket.on("deleteStack", async (name : unknown, callback) => {
onStackMutation("deleteStack", async (name : unknown, callback) => {
try {
checkLogin(socket);
if (typeof(name) !== "string") {
throw new ValidationError("Name must be a string");
}
@ -55,6 +73,7 @@ export class DockerSocketHandler extends AgentSocketHandler {
throw e;
}
server.imageVulnerabilityScan.forget(name);
server.sendStackList();
callbackResult({
ok: true,
@ -84,12 +103,61 @@ export class DockerSocketHandler extends AgentSocketHandler {
callbackResult({
ok: true,
stack: await stack.toJSON(socket.endpoint),
autoUpdate: await server.stackAutoUpdate.getPolicy(stack),
imageScanSupported: stack.isManagedByDockge,
}, callback);
} catch (e) {
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
agentSocket.on("requestStackList", async (callback) => {
try {
@ -106,9 +174,8 @@ export class DockerSocketHandler extends AgentSocketHandler {
});
// startStack
agentSocket.on("startStack", async (stackName : unknown, callback) => {
onStackMutation("startStack", async (stackName : unknown, callback) => {
try {
checkLogin(socket);
if (typeof(stackName) !== "string") {
throw new ValidationError("Stack name must be a string");
@ -131,9 +198,8 @@ export class DockerSocketHandler extends AgentSocketHandler {
});
// stopStack
agentSocket.on("stopStack", async (stackName : unknown, callback) => {
onStackMutation("stopStack", async (stackName : unknown, callback) => {
try {
checkLogin(socket);
if (typeof(stackName) !== "string") {
throw new ValidationError("Stack name must be a string");
@ -147,15 +213,16 @@ export class DockerSocketHandler extends AgentSocketHandler {
msgi18n: true,
}, callback);
server.sendStackList();
stack.leaveCombinedTerminal(socket);
} catch (e) {
callbackError(e, callback);
}
});
// restartStack
agentSocket.on("restartStack", async (stackName : unknown, callback) => {
onStackMutation("restartStack", async (stackName : unknown, callback) => {
try {
checkLogin(socket);
if (typeof(stackName) !== "string") {
throw new ValidationError("Stack name must be a string");
@ -175,9 +242,8 @@ export class DockerSocketHandler extends AgentSocketHandler {
});
// updateStack
agentSocket.on("updateStack", async (stackName : unknown, callback) => {
onStackMutation("updateStack", async (stackName : unknown, callback) => {
try {
checkLogin(socket);
if (typeof(stackName) !== "string") {
throw new ValidationError("Stack name must be a string");
@ -197,9 +263,20 @@ export class DockerSocketHandler extends AgentSocketHandler {
});
// down stack
agentSocket.on("downStack", async (stackName : unknown, callback) => {
onStackMutation("setStackAutoUpdate", async (name, enabled, 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 {
checkLogin(socket);
if (typeof(stackName) !== "string") {
throw new ValidationError("Stack name must be a string");
@ -238,6 +315,81 @@ 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
agentSocket.on("getDockerNetworkList", async (callback) => {
try {
@ -253,7 +405,7 @@ export class DockerSocketHandler extends AgentSocketHandler {
});
}
async saveStack(server : DockgeServer, name : unknown, composeYAML : unknown, composeENV : unknown, isAdd : unknown) : Promise<Stack> {
async saveStack(server : DockgeServer, name : unknown, composeYAML : unknown, composeENV : unknown, isAdd : unknown, revision?: unknown) : Promise<Stack> {
// Check types
if (typeof(name) !== "string") {
throw new ValidationError("Name must be a string");
@ -267,9 +419,12 @@ export class DockerSocketHandler extends AgentSocketHandler {
if (typeof(isAdd) !== "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);
await stack.save(isAdd);
await stack.save(isAdd, revision as string | undefined);
return stack;
}

87
backend/auth-session.ts Normal file
View File

@ -0,0 +1,87 @@
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,6 +37,8 @@ import { AgentSocketHandler } from "./agent-socket-handler";
import { AgentSocket } from "../common/agent-socket";
import { ManageAgentSocketHandler } from "./socket-handlers/manage-agent-socket-handler";
import { Terminal } from "./terminal";
import { StackAutoUpdate } from "./stack-auto-update";
import { ImageVulnerabilityScan } from "./image-vulnerability-scan";
export class DockgeServer {
app : Express;
@ -78,7 +80,11 @@ export class DockgeServer {
jwtSecret : string = "";
private authModeRevision = 0;
stacksDir : string = "";
stackAutoUpdate = new StackAutoUpdate(this);
imageVulnerabilityScan = new ImageVulnerabilityScan(this);
/**
*
@ -299,21 +305,22 @@ export class DockgeServer {
// 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
dockgeSocket.on("disconnect", () => {
log.info("server", "Socket disconnected!");
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", () => {
@ -327,8 +334,12 @@ export class DockgeServer {
}
}
async afterLogin(socket : DockgeSocket, user : User) {
async afterLogin(socket : DockgeSocket, user : User, authBypassed = false) {
if (!socket.connected) {
return;
}
socket.userID = user.id;
socket.authBypassed = authBypassed;
socket.join(user.id.toString());
this.sendInfo(socket);
@ -404,6 +415,7 @@ export class DockgeServer {
});
checkVersion.startInterval();
this.stackAutoUpdate.start();
});
gracefulShutdown(this.httpServer, {
@ -411,7 +423,7 @@ export class DockgeServer {
timeout: 30000, // timeout: 30 secs
development: false, // not in dev mode
forceExit: true, // triggers process.exit() at the end of shutdown process
onShutdown: this.shutdownFunction, // shutdown function (async) - e.g. for cleanup DB, ...
onShutdown: this.shutdownFunction.bind(this), // shutdown function (async) - e.g. for cleanup DB, ...
finally: this.finalFunction, // finally function (sync) - e.g. for logging
});
@ -637,6 +649,35 @@ export class DockgeServer {
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() {
return path.resolve(this.stacksDir);
}
@ -652,6 +693,8 @@ export class DockgeServer {
// TODO: Close all terminals?
this.stackAutoUpdate.stop();
await this.imageVulnerabilityScan.stop();
await Database.close();
Settings.stopCacheCleaner();
}
@ -683,6 +726,37 @@ 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() {
return this.config.sslKey && this.config.sslCert;
}

View File

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

View File

@ -0,0 +1,12 @@
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,6 +23,7 @@ export class Agent extends BeanModel {
url: this.url,
username: this.username,
endpoint: this.endpoint,
name: this.name,
};
}

View File

@ -1,7 +1,6 @@
import jwt from "jsonwebtoken";
import { R } from "redbean-node";
import { BeanModel } from "redbean-node/dist/bean-model";
import { generatePasswordHash, shake256, SHAKE256_LENGTH } from "../password-hash";
import { generatePasswordHash } from "../password-hash";
export class User extends BeanModel {
/**
@ -27,20 +26,6 @@ export class User extends BeanModel {
await User.resetPassword(this.id, 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;

View File

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

View File

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

View File

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

View File

@ -20,7 +20,7 @@ export class ManageAgentSocketHandler extends SocketHandler {
let data = requestData as LooseObject;
let manager = socket.instanceManager;
await manager.test(data.url, data.username, data.password);
await manager.add(data.url, data.username, data.password);
await manager.add(data.url, data.username, data.password, data.name);
// connect to the agent
manager.connect(data.url, data.username, data.password);
@ -66,5 +66,27 @@ export class ManageAgentSocketHandler extends SocketHandler {
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

@ -0,0 +1,337 @@
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})`);
}
}
}

109
backend/stack-files.ts Normal file
View File

@ -0,0 +1,109 @@
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,5 +1,6 @@
import { DockgeServer } from "./dockge-server";
import fs, { promises as fsAsync } from "fs";
import { createHash } from "node:crypto";
import { log } from "./log";
import yaml from "yaml";
import { DockgeSocket, fileExists, ValidationError } from "./util-server";
@ -19,6 +20,8 @@ import {
import { InteractiveTerminal, Terminal } from "./terminal";
import childProcessAsync from "promisify-child-process";
import { Settings } from "./settings";
import { analyzeEnv } from "../common/env-file";
import { saveStackFiles } from "./stack-files";
export class Stack {
@ -33,6 +36,27 @@ export class Stack {
protected combinedTerminal? : Terminal;
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) {
this.name = name;
@ -75,6 +99,7 @@ export class Stack {
composeYAML: this.composeYAML,
composeENV: this.composeENV,
primaryHostname,
revision: this.revision,
};
}
@ -111,6 +136,10 @@ export class Stack {
return this._status;
}
get revision(): string {
return createHash("sha256").update(JSON.stringify([ this._composeFileName, this.composeYAML, this.composeENV ])).digest("hex");
}
validate() {
// Check name, allows [a-z][0-9] _ - only
if (!this.name.match(/^[a-z0-9_-]+$/)) {
@ -118,15 +147,15 @@ export class Stack {
}
// Check YAML format
yaml.parse(this.composeYAML);
let lines = this.composeENV.split("\n");
// Check if the .env is able to pass docker-compose
// Prevent "setenv: The parameter is incorrect"
// It only happens when there is one line and it doesn't contain "="
if (lines.length === 1 && !lines[0].includes("=") && lines[0].length > 0) {
throw new ValidationError("Invalid .env format");
const config = yaml.parse(this.composeYAML);
if (config !== null && (typeof config !== "object" || Array.isArray(config))) {
throw new ValidationError("editorYamlMapping");
}
if (config?.services && (typeof config.services !== "object" || Array.isArray(config.services))) {
throw new ValidationError("editorServicesMapping");
}
if (analyzeEnv(this.composeENV).some(issue => issue.severity === "error")) {
throw new ValidationError("editorInvalidEnv");
}
}
@ -174,11 +203,32 @@ export class Stack {
/**
* Save the stack to the disk
* @param isAdd
* @param expectedRevision Version loaded by the editor, omitted by legacy clients
*/
async save(isAdd : boolean) {
async save(isAdd : boolean, expectedRevision?: string) {
this.validate();
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
if (isAdd) {
@ -192,23 +242,40 @@ export class Stack {
if (!await fileExists(dir)) {
throw new ValidationError("Stack not found");
}
checkRevision();
}
// Write or overwrite the compose.yaml
await fsAsync.writeFile(path.join(dir, this._composeFileName), this.composeYAML);
const envPath = path.join(dir, ".env");
// Write or overwrite the .env
// If .env is not existing and the composeENV is empty, we don't need to write it
if (await fileExists(envPath) || this.composeENV.trim() !== "") {
await fsAsync.writeFile(envPath, this.composeENV);
try {
if (owner) {
await fsAsync.lchown(dir, owner.uid, owner.gid);
}
await saveStackFiles([
{
path: path.join(dir, this._composeFileName),
content: this.composeYAML,
mode: 0o644,
},
{
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> {
const terminalName = getComposeTerminalName(socket.endpoint, this.name);
let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", this.getComposeOptions("up", "-d", "--remove-orphans"), this.path);
let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", this.getComposeOptions("config", "--quiet"), 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) {
throw new Error("Failed to deploy, please check the terminal output for more information.");
}
@ -510,7 +577,7 @@ export class Stack {
}
async getServiceStatusList() {
let statusList = new Map<string, { state: string, ports: string[] }>();
let statusList = new Map<string, Array<object>>();
try {
let res = await childProcessAsync.spawn("docker", this.getComposeOptions("ps", "--format", "json"), {
@ -524,22 +591,23 @@ export class Stack {
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) {
try {
let obj = JSON.parse(line);
let ports = (obj.Ports as string).split(/,\s*/).filter((s) => {
return s.indexOf("->") >= 0;
});
if (obj.Health === "") {
statusList.set(obj.Service, {
state: obj.State,
ports: ports
});
if (obj instanceof Array) {
obj.forEach(addLine);
} else {
statusList.set(obj.Service, {
state: obj.Health,
ports: ports
});
addLine(obj);
}
} catch (e) {
}
@ -550,6 +618,35 @@ export class Stack {
log.error("getServiceStatusList", e);
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,14 +7,12 @@ import { R } from "redbean-node";
import { verifyPassword } from "./password-hash";
import fs from "fs";
import { AgentManager } from "./agent-manager";
export interface JWTDecoded {
username : string;
h? : string;
}
import type { AuthSession } from "./auth-session";
export interface DockgeSocket extends Socket {
userID: number;
authBypassed?: boolean;
authSession?: AuthSession;
consoleTerminal? : Terminal;
instanceManager : AgentManager;
endpoint : string;

71
common/env-file.ts Normal file
View File

@ -0,0 +1,71 @@
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,12 +16,30 @@ RUN npm ci --omit=dev
# ⭐ Main Image
############################################
FROM louislam/dockge:base AS release
ARG TARGETARCH
WORKDIR /app
COPY --chown=node:node --from=build_healthcheck /app/extra/healthcheck /app/extra/healthcheck
COPY --from=build /app/node_modules /app/node_modules
COPY --chown=node:node . .
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.
# Read more:

View File

@ -11,23 +11,32 @@ declare module 'vue' {
Appearance: typeof import('./src/components/settings/Appearance.vue')['default']
ArrayInput: typeof import('./src/components/ArrayInput.vue')['default']
ArraySelect: typeof import('./src/components/ArraySelect.vue')['default']
BButton: typeof import('bootstrap-vue-next')['BButton']
BDropdown: typeof import('bootstrap-vue-next')['BDropdown']
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']
Confirm: typeof import('./src/components/Confirm.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']
GlobalEnv: typeof import('./src/components/settings/GlobalEnv.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']
NetworkInput: typeof import('./src/components/NetworkInput.vue')['default']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
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']
StackListItem: typeof import('./src/components/StackListItem.vue')['default']
Terminal: typeof import('./src/components/Terminal.vue')['default']
TwoFADialog: typeof import('./src/components/TwoFADialog.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>
<div class="shadow-box big-padding mb-3 container">
<div class="row">
<div class="col-7">
<div class="col-5">
<h4>{{ name }}</h4>
<div class="image mb-2">
<span class="me-1">{{ imageName }}:</span><span class="tag">{{ imageTag }}</span>
@ -14,12 +14,41 @@
</a>
</div>
</div>
<div class="col-5">
<div class="col-7">
<div class="function">
<router-link v-if="!isEditMode" class="btn btn-normal" :to="terminalRouteLink" disabled="">
<font-awesome-icon icon="terminal" />
Bash
</router-link>
<div class="btn-group me-2" role="group">
<router-link v-if="!isEditMode && (status === 'running' || status === 'healthy')" class="btn btn-normal" :to="terminalRouteLink" disabled="">
<font-awesome-icon icon="terminal" />
Bash
</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>
@ -35,6 +64,32 @@
{{ $t("deleteContainer") }}
</button>
</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>
<div v-if="isEditMode && showConfig" class="config mt-3">
@ -138,10 +193,12 @@
import { defineComponent } from "vue";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import { parseDockerPort } from "../../../common/util-common";
import DockerStat from "./DockerStat.vue";
export default defineComponent({
components: {
FontAwesomeIcon,
DockerStat
},
props: {
name: {
@ -156,20 +213,24 @@ export default defineComponent({
type: Boolean,
default: false,
},
status: {
type: String,
default: "N/A",
serviceStatus: {
type: Object,
default: null,
},
ports: {
type: Array,
dockerStats: {
type: Object,
default: null
}
},
emits: [
"start-service",
"stop-service",
"restart-service"
],
data() {
return {
showConfig: false,
expandedStats: false,
};
},
computed: {
@ -234,6 +295,10 @@ export default defineComponent({
return this.jsonObject.services[this.name];
},
serviceCount() {
return Object.keys(this.jsonObject.services).length;
},
jsonObject() {
return this.$parent.$parent.jsonConfig;
},
@ -270,6 +335,22 @@ export default defineComponent({
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() {
if (this.first) {
@ -288,6 +369,16 @@ export default defineComponent({
remove() {
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>
@ -312,5 +403,10 @@ export default defineComponent({
align-items: center;
justify-content: end;
}
.stats {
font-size: 0.8rem;
color: #6c757d;
}
}
</style>

View File

@ -0,0 +1,94 @@
<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

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

View File

@ -0,0 +1,495 @@
<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,447 +1,217 @@
<template>
<div class="shadow-box mb-3" :style="boxStyle">
<div class="list-header">
<div class="header-top">
<!-- TODO -->
<button v-if="false" class="btn btn-outline-normal ms-2" :class="{ 'active': selectMode }" type="button" @click="selectMode = !selectMode">
{{ $t("Select") }}
</button>
<nav class="stack-nav-panel" :aria-label="$t('stackListTitle')">
<div class="stack-nav-header">
<slot name="title">
<h2 class="stack-nav-title">{{ $t("stackListTitle") }}</h2>
</slot>
<router-link to="/compose" class="stack-nav-button stack-nav-primary" @click.left.exact="$emit('navigate')">
<font-awesome-icon icon="plus" aria-hidden="true" /> {{ $t("stackListNew") }}
</router-link>
<slot name="close" />
</div>
<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 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>
<!-- TODO -->
<div v-if="false" class="header-filter">
<!--<StackListFilter :filterState="filterState" @update-filter="updateFilter" />-->
<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>
</div>
<div class="stack-nav-results">
<p v-if="!$root.socketIO.connected" class="stack-nav-message" role="status">
{{ $t("stackListStale") }}
</p>
<div :key="filtersActive ? 'filtered' : 'all'">
<CollapsibleRoot
v-for="agent in visibleAgents" :key="agent.endpoint" class="stack-nav-group" :default-open="true"
>
<CollapsibleTrigger v-if="agent.stacks.length" class="stack-nav-group-heading" type="button">
<font-awesome-icon icon="chevron-down" class="stack-nav-chevron" aria-hidden="true" />
<span class="stack-nav-agent">{{ agent.name }}</span>
<span v-if="agent.connection !== 'online'" class="stack-nav-connection" :data-state="agent.connection">
{{ $t(agent.connection === "offline" ? "agentOffline" : "connecting") }}
</span>
</CollapsibleTrigger>
<div v-else class="stack-nav-group-heading">
<span class="stack-nav-agent">{{ agent.name }}</span>
<span class="stack-nav-connection" :data-state="agent.connection">
{{ $t(agent.connection === "offline" ? "agentOffline" : "connecting") }}
</span>
</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>
<!-- TODO: Selection Controls -->
<div v-if="selectMode && false" class="selection-controls px-2 pt-2">
<input
v-model="selectAll"
class="form-check-input select-input"
type="checkbox"
/>
<button class="btn-outline-normal" @click="pauseDialog"><font-awesome-icon icon="pause" size="sm" /> {{ $t("Pause") }}</button>
<button class="btn-outline-normal" @click="resumeSelected"><font-awesome-icon icon="play" size="sm" /> {{ $t("Resume") }}</button>
<span v-if="selectedStackCount > 0">
{{ $t("selectedStackCount", [ selectedStackCount ]) }}
</span>
<div v-if="emptyMessage" class="stack-nav-message">
<p>{{ $t(emptyMessage) }}</p>
<router-link v-if="emptyMessage === 'stackListEmpty'" to="/compose" @click.left.exact="$emit('navigate')">
{{ $t("addFirstStackMsg") }}
</router-link>
</div>
</div>
<div ref="stackList" class="stack-list" :class="{ scrollbar: scrollbar }" :style="stackListStyle">
<div v-if="Object.keys(sortedStackList).length === 0" class="text-center mt-3">
<router-link to="/compose">{{ $t("addFirstStackMsg") }}</router-link>
</div>
<StackListItem
v-for="(item, index) in sortedStackList"
:key="index"
:stack="item"
:isSelectMode="selectMode"
:isSelected="isSelected"
:select="select"
:deselect="deselect"
/>
</div>
</div>
<Confirm ref="confirmPause" :yes-text="$t('Yes')" :no-text="$t('No')" @yes="pauseSelected">
{{ $t("pauseStackMsg") }}
</Confirm>
</nav>
</template>
<script>
import Confirm from "../components/Confirm.vue";
import StackListItem from "../components/StackListItem.vue";
import { CREATED_FILE, CREATED_STACK, EXITED, RUNNING, UNKNOWN } from "../../../common/util-common";
import { CollapsibleContent, CollapsibleRoot, CollapsibleTrigger } from "@ark-ui/vue/collapsible";
import { useId } from "vue";
import StackListItem from "./StackListItem.vue";
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 {
components: {
Confirm,
CollapsibleContent,
CollapsibleRoot,
CollapsibleTrigger,
StackListItem,
},
props: {
/** Should the scrollbar be shown */
scrollbar: {
type: Boolean,
},
emits: [ "navigate" ],
setup() {
return {
hostId: useId(),
statusId: useId(),
};
},
data() {
return {
searchText: "",
selectMode: false,
selectAll: false,
disableSelectAllWatcher: false,
selectedStacks: {},
windowTop: 0,
filterState: {
status: null,
active: null,
tags: null,
}
host: null,
status: "",
statuses,
};
},
computed: {
/**
* Improve the sticky appearance of the list by increasing its
* height as user scrolls down.
* Not used on mobile.
* @returns {object} Style for stack list
*/
boxStyle() {
if (window.innerWidth > 550) {
return {
height: `calc(100vh - 160px + ${this.windowTop}px)`,
};
} else {
return {
height: "calc(100vh - 160px)",
};
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 ];
},
/**
* 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;
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 m1.name.localeCompare(m2.name);
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 };
});
return result;
},
isDarkTheme() {
return document.body.classList.contains("dark");
visibleAgents() {
return this.filteredAgents.filter(agent => agent.stacks.length || agent.connection !== "online");
},
stackListStyle() {
//let listHeaderHeight = 107;
let listHeaderHeight = 60;
if (this.selectMode) {
listHeaderHeight += 42;
}
return {
"height": `calc(100% - ${listHeaderHeight}px)`
};
resultCount() {
return this.filteredAgents.reduce((total, agent) => total + agent.stacks.length, 0);
},
selectedStackCount() {
return Object.keys(this.selectedStacks).length;
loading() {
return this.filteredAgents.some(agent => agent.connection !== "offline" && !agent.loaded);
},
/**
* 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 !== "";
}
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: {
searchText() {
for (let stack of this.sortedStackList) {
if (!this.selectedStacks[stack.id]) {
if (this.selectAll) {
this.disableSelectAllWatcher = true;
this.selectAll = false;
}
break;
}
agents(agents) {
if (this.host !== null && !agents.some(agent => agent.endpoint === this.host)) {
this.host = null;
}
},
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}
* Build the label and connection state for an agent, including agents without stacks.
* @param {string} endpoint Agent endpoint, or an empty string for the local host
* @returns {object} Agent shown in the stack navigator
*/
onScroll() {
if (window.top.scrollY <= 133) {
this.windowTop = window.top.scrollY;
} else {
this.windowTop = 133;
}
describeAgent(endpoint) {
const loaded = endpoint ? Object.hasOwn(this.$root.allAgentStackList, endpoint) : this.$root.stackListLoaded;
return {
endpoint,
name: endpoint ? this.$root.agentList[endpoint]?.name || endpoint : this.$t("stackListLocal"),
connection: this.$root.agentStatusList[endpoint] || (loaded ? "online" : "connecting"),
loaded,
stacks: [],
};
},
/**
* Clear the search bar
* Restore the unfiltered list.
* @returns {void}
*/
clearSearchText() {
clearFilters() {
this.searchText = "";
},
/**
* 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();
this.host = null;
this.status = "";
this.$refs.search.focus();
},
},
};
</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,181 +1,43 @@
<template>
<router-link :to="url" :class="{ 'dim' : !stack.isManagedByDockge }" class="item">
<Uptime :stack="stack" :fixed-width="true" class="me-2" />
<div class="title">
<span>{{ stackName }}</span>
<div v-if="$root.agentCount > 1" class="endpoint">{{ endpointDisplay }}</div>
</div>
<router-link :to="url" class="stack-nav-item" @click.left.exact="$emit('navigate')">
<span class="stack-nav-item-copy">
<span class="stack-nav-name">{{ stack.name }}</span>
<span class="stack-nav-item-meta">
{{ hostName }}<template v-if="!stack.isManagedByDockge"> · {{ $t("stackListUnmanaged") }}</template>
</span>
</span>
<span class="stack-nav-badge" :data-state="status">
{{ $t(status) }}
</span>
</router-link>
</template>
<script>
import Uptime from "./Uptime.vue";
import { statusNameShort } from "../../../common/util-common";
export default {
components: {
Uptime
},
props: {
/** Stack this represents */
/** Stack to link to */
stack: {
type: Object,
default: null,
required: true,
},
/** If the user is in select mode */
isSelectMode: {
type: Boolean,
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: () => {}
/** Display name of the host running the stack */
hostName: {
type: String,
required: true,
},
},
data() {
return {
isCollapsed: true,
};
},
emits: [ "navigate" ],
computed: {
endpointDisplay() {
return this.$root.endpointDisplayFunction(this.stack.endpoint);
status() {
const status = statusNameShort(this.stack.status);
return status === "?" ? "stackListUnknown" : status;
},
url() {
if (this.stack.endpoint) {
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);
}
const name = encodeURIComponent(this.stack.name);
return this.stack.endpoint ? `/compose/${name}/${encodeURIComponent(this.stack.endpoint)}` : `/compose/${name}`;
},
},
};
</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,22 +20,24 @@ export default {
props: {
name: {
type: String,
require: true,
required: true,
},
endpoint: {
type: String,
require: true,
required: true,
},
// Require if mode is interactive
stackName: {
type: String,
default: "",
},
// Require if mode is interactive
serviceName: {
type: String,
default: "",
},
// Require if mode is interactive
@ -102,7 +104,7 @@ export default {
this.terminal.focus();
// 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
this.terminal.onSelectionChange(() => {
@ -143,7 +145,7 @@ export default {
window.removeEventListener("resize", this.onResizeEvent); // Remove the resize event listener from the window object.
this.$root.unbindTerminal(this.name);
this.terminal.dispose();
this.$refs.terminal?.removeEventListener('contextmenu', this.handleContextMenu);
this.$refs.terminal?.removeEventListener("contextmenu", this.handleContextMenu);
},
methods: {
@ -206,7 +208,7 @@ export default {
const afterCursor = this.terminalInputBuffer.slice(this.cursorPosition);
this.terminalInputBuffer = beforeCursor + afterCursor;
this.cursorPosition--;
// Redraw the line
this.terminal.write("\b" + afterCursor + " \b".repeat(afterCursor.length + 1));
}
@ -216,7 +218,7 @@ export default {
const beforeCursor = this.terminalInputBuffer.slice(0, this.cursorPosition);
const afterCursor = this.terminalInputBuffer.slice(this.cursorPosition + 1);
this.terminalInputBuffer = beforeCursor + afterCursor;
// Redraw the line from cursor position
this.terminal.write(afterCursor + " \b".repeat(afterCursor.length + 1));
}
@ -312,19 +314,19 @@ export default {
// For main terminal, insert text at current cursor position
const beforeCursor = this.terminalInputBuffer.slice(0, this.cursorPosition);
const afterCursor = this.terminalInputBuffer.slice(this.cursorPosition);
// Update the buffer with inserted text
this.terminalInputBuffer = beforeCursor + text + afterCursor;
// Clear the current line and rewrite it
this.clearCurrentLine();
this.terminal.write(this.terminalInputBuffer);
// Move cursor to the correct position (after the pasted text)
this.cursorPosition += text.length;
const backspaces = "\b".repeat(afterCursor.length);
this.terminal.write(backspaces);
} else if (this.mode === "interactive") {
// For interactive terminal, send directly to server
this.$root.emitAgent(this.endpoint, "terminalInput", this.name, text, (res) => {
@ -341,7 +343,7 @@ export default {
handleContextMenu(event) {
// Prevent default context menu
event.preventDefault();
// Only handle paste for modes that support input
if (this.mode === "mainTerminal" || this.mode === "interactive") {
this.handlePaste();

View File

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

View File

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

View File

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

View File

@ -12,17 +12,125 @@
"registry": "Registry",
"compose": "Compose",
"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",
"deployStack": "Deploy",
"deleteStack": "Delete",
"stopStack": "Stop",
"restartStack": "Restart",
"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",
"downStack": "Stop & Inactive",
"editStack": "Edit",
"discardStack": "Discard",
"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",
"deleteStackMsg": "Are you sure you want to delete this stack?",
"cancel": "Cancel",
@ -47,8 +155,10 @@
"deleteContainer": "Delete",
"addContainer": "Add Container",
"addNetwork": "Add Network",
"disableauth.message1": "Are you sure want to <strong>disable authentication</strong>?",
"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.message1": "Are you sure want to {disableAuth}?",
"disableauth.message2": "It is designed for scenarios {scenarios}",
"disableAuth": "disable authentication",
"scenarios": "where you intend to implement third-party authentication",
"passwordNotMatchMsg": "The repeat password does not match.",
"autoGet": "Auto Get",
"add": "Add",
@ -80,6 +190,7 @@
"Password": "Password",
"Settings": "Settings",
"Logout": "Logout",
"authLogoutFailed": "Dockge could not confirm that this session ended. Please try again while connected.",
"Lowercase only": "Lowercase only",
"Convert to Compose": "Convert to Compose",
"Docker Run": "Docker Run",
@ -116,6 +227,8 @@
"removeAgentMsg": "Are you sure you want to remove this agent?",
"GlobalEnv": "Global .env",
"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",
"Deployed": "Deployed",
"Deleted": "Deleted",
@ -131,9 +244,18 @@
"Network name...": "Network name...",
"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.",
"CPU": "CPU",
"memory": "Memory",
"memoryAbbreviated": "Mem",
"networkIO": "Network I/O",
"blockIO": "Block I/O",
"Console is not enabled": "Console is not enabled",
"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 <code>rm -rf</code>" ,
"ConsoleNotEnabledMSG3": "If you understand the risk, you can enable it by setting <code>DOCKGE_ENABLE_CONSOLE=true</code> in the environment variables.",
"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.",
"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}",
"ConsoleNotEnabledMSG3": "If you understand the risk, you can enable it by setting {envVar} 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?"
}

View File

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

View File

@ -4,19 +4,19 @@
<h1 v-if="isAdd" class="mb-3">{{ $t("compose") }}</h1>
<h1 v-else class="mb-3">
<Uptime :stack="globalStack" :pill="true" /> {{ stack.name }}
<span v-if="$root.agentCount > 1" class="agent-name">
<span v-if="$root.agentCount > 1 && endpoint !== ''" class="agent-name">
({{ endpointDisplay }})
</span>
</h1>
<div v-if="stack.isManagedByDockge" class="mb-3">
<div class="btn-group me-2" role="group">
<button v-if="isEditMode" class="btn btn-primary" :disabled="processing" @click="deployStack">
<button v-if="isEditMode" class="btn btn-primary" :disabled="processing || hasConfigErrors" @click="deployStack">
<font-awesome-icon icon="rocket" class="me-1" />
{{ $t("deployStack") }}
</button>
<button v-if="isEditMode" class="btn btn-normal" :disabled="processing" @click="saveStack">
<button v-if="isEditMode" class="btn btn-normal" :disabled="processing || hasConfigErrors || (!isAdd && !dirty)" @click="saveStack">
<font-awesome-icon icon="save" class="me-1" />
{{ $t("saveStackDraft") }}
</button>
@ -61,10 +61,33 @@
</button>
</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 -->
<div v-if="urls.length > 0" class="mb-3">
<a v-for="(url, index) in urls" :key="index" target="_blank" :href="url.url">
<span class="badge bg-secondary me-2">{{ url.display }}</span>
<a v-for="(urlItem, index) in urls" :key="index" target="_blank" :href="urlItem.url">
<span class="badge bg-secondary me-2">{{ urlItem.display }}</span>
</a>
</div>
@ -81,7 +104,7 @@
></Terminal>
</transition>
<div v-if="stack.isManagedByDockge" class="row">
<fieldset v-if="stack.isManagedByDockge" class="row" :disabled="processing">
<div class="col-lg-6">
<!-- General -->
<div v-if="isAdd">
@ -98,8 +121,8 @@
<div class="mt-3">
<label for="name" class="form-label">{{ $t("dockgeAgent") }}</label>
<select v-model="stack.endpoint" class="form-select">
<option v-for="(agent, endpoint) in $root.agentList" :key="endpoint" :value="endpoint" :disabled="$root.agentStatusList[endpoint] != 'online'">
({{ $root.agentStatusList[endpoint] }}) {{ (endpoint) ? endpoint : $t("currentEndpoint") }}
<option v-for="(agent, agentEndpoint) in $root.agentList" :key="agentEndpoint" :value="agentEndpoint" :disabled="$root.agentStatusList[agentEndpoint] != 'online'">
({{ $root.agentStatusList[agentEndpoint] }}) {{ (agent.name !== '') ? agent.name : agent.url || $t("Current") }}
</option>
</select>
</div>
@ -128,8 +151,11 @@
:name="name"
:is-edit-mode="isEditMode"
:first="name === Object.keys(jsonConfig.services)[0]"
:status="serviceStatusList[name]?.state"
:ports="serviceStatusList[name]?.ports"
:serviceStatus="serviceStatusList[name]"
:dockerStats="dockerStats"
@start-service="startService"
@stop-service="stopService"
@restart-service="restartService"
/>
</div>
@ -164,45 +190,13 @@
</div>
</div>
<div class="col-lg-6">
<h4 class="mb-3">{{ stack.composeFileName }}</h4>
<!-- YAML editor -->
<div class="shadow-box mb-3 editor-box" :class="{'edit-mode' : isEditMode}">
<code-mirror
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>
<StackConfigEditor
v-if="!processing || stack.composeYAML !== undefined"
v-model:yaml="stack.composeYAML" v-model:env="stack.composeENV"
class="mb-3" :file-name="stack.composeFileName || 'compose.yaml'"
:editable="isEditMode" :disabled="processing" :dirty="dirty"
@save="saveStack"
/>
<div v-if="isEditMode">
<!-- Volumes -->
@ -228,7 +222,7 @@
<prism-editor v-if="false" v-model="yamlConfig" class="yaml-editor" :highlight="highlighter" line-numbers @input="yamlCodeChange"></prism-editor>
</div>-->
</div>
</div>
</fieldset>
<div v-if="!stack.isManagedByDockge && !processing">
{{ $t("stackNotManagedByDockgeMsg") }}
@ -243,11 +237,8 @@
</template>
<script>
import CodeMirror from "vue-codemirror6";
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 ImageVulnerabilities from "../components/ImageVulnerabilities.vue";
import StackConfigEditor from "../components/StackConfigEditor.vue";
import { parseDocument, Document } from "yaml";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
@ -263,7 +254,8 @@ import {
import { BModal } from "bootstrap-vue-next";
import NetworkInput from "../components/NetworkInput.vue";
import dotenv from "dotenv";
import { ref } from "vue";
import { markRaw } from "vue";
import { analyzeEnv } from "../../../common/env-file";
const template = `
services:
@ -275,15 +267,15 @@ services:
`;
const envDefault = "# VARIABLE=value #comment";
let yamlErrorTimeout = null;
let serviceStatusTimeout = null;
let dockerStatsTimeout = null;
export default {
components: {
ImageVulnerabilities,
StackConfigEditor,
NetworkInput,
FontAwesomeIcon,
CodeMirror,
BModal,
},
beforeRouteUpdate(to, from, next) {
@ -292,39 +284,19 @@ export default {
beforeRouteLeave(to, from, 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() {
return {
jsonConfig: {},
envsubstJSONConfig: {},
yamlError: "",
yamlDoc: null,
updatingFromYaml: false,
savedConfig: null,
saveError: "",
processing: true,
autoUpdate: null,
autoUpdateSaving: false,
imageScanSupported: false,
showProgressTerminal: false,
progressTerminalRows: PROGRESS_TERMINAL_ROWS,
combinedTerminalRows: COMBINED_TERMINAL_ROWS,
@ -333,14 +305,24 @@ export default {
},
serviceStatusList: {},
dockerStats: {},
isEditMode: false,
submitted: false,
showDeleteDialog: false,
newContainerName: "",
stopServiceStatusTimeout: false,
stopDockerStatsTimeout: false,
};
},
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() {
return this.$root.endpointDisplayFunction(this.endpoint);
},
@ -425,28 +407,21 @@ export default {
watch: {
"stack.composeYAML": {
handler() {
if (this.editorFocus) {
console.debug("yaml code changed");
this.yamlCodeChange();
}
this.yamlCodeChange();
},
deep: true,
},
"stack.composeENV": {
handler() {
if (this.editorFocus) {
console.debug("env code changed");
this.yamlCodeChange();
}
this.updateEnvironmentPreview();
},
deep: true,
},
jsonConfig: {
handler() {
if (!this.editorFocus) {
console.debug("jsonConfig changed");
if (!this.updatingFromYaml && !this.yamlError) {
let doc = new Document(this.jsonConfig);
@ -456,10 +431,11 @@ export default {
}
this.stack.composeYAML = doc.toString();
this.yamlDoc = doc;
this.yamlDoc = markRaw(doc);
}
},
deep: true,
flush: "sync",
},
$route(to, from) {
@ -467,6 +443,7 @@ export default {
}
},
mounted() {
window.addEventListener("beforeunload", this.confirmPageExit);
if (this.isAdd) {
this.processing = false;
this.isEditMode = true;
@ -497,6 +474,7 @@ export default {
};
this.yamlCodeChange();
this.captureSavedConfig();
} else {
this.stack.name = this.$route.params.stackName;
@ -504,9 +482,11 @@ export default {
}
this.requestServiceStatus();
this.requestDockerStats();
},
unmounted() {
window.removeEventListener("beforeunload", this.confirmPageExit);
this.exitAction();
},
methods: {
startServiceStatusTimeout() {
@ -516,6 +496,13 @@ export default {
}, 5000);
},
startDockerStatsTimeout() {
clearTimeout(dockerStatsTimeout);
dockerStatsTimeout = setTimeout(async () => {
this.requestDockerStats();
}, 5000);
},
requestServiceStatus() {
// Do not request if it is add mode
if (this.isAdd) {
@ -532,8 +519,19 @@ export default {
});
},
requestDockerStats() {
this.$root.emitAgent(this.endpoint, "dockerStats", (res) => {
if (res.ok) {
this.dockerStats = res.dockerStats;
}
if (!this.stopDockerStatsTimeout) {
this.startDockerStatsTimeout();
}
});
},
exitConfirm(next) {
if (this.isEditMode) {
if (this.dirty) {
if (confirm(this.$t("confirmLeaveStack"))) {
this.exitAction();
next();
@ -547,9 +545,14 @@ export default {
},
exitAction() {
if (this.stopServiceStatusTimeout && this.stopDockerStatsTimeout) {
return;
}
console.log("exitAction");
this.stopServiceStatusTimeout = true;
this.stopDockerStatsTimeout = true;
clearTimeout(serviceStatusTimeout);
clearTimeout(dockerStatsTimeout);
// Leave Combined Terminal
console.debug("leaveCombinedTerminal", this.endpoint, this.stack.name);
@ -565,19 +568,52 @@ export default {
this.$root.emitAgent(this.endpoint, "getStack", this.stack.name, (res) => {
if (res.ok) {
this.stack = res.stack;
this.autoUpdate = res.autoUpdate ?? null;
this.imageScanSupported = res.imageScanSupported === true;
this.yamlCodeChange();
this.captureSavedConfig();
this.saveError = "";
this.processing = false;
this.bindTerminal();
} else {
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() {
if (this.hasConfigErrors) {
return;
}
this.processing = true;
if (!this.jsonConfig.services) {
if (!this.jsonConfig.services || Object.keys(this.jsonConfig.services).length === 0) {
this.$root.toastError("No services found in compose.yaml");
this.processing = false;
return;
@ -606,29 +642,61 @@ export default {
this.bindTerminal();
this.$root.emitAgent(this.stack.endpoint, "deployStack", this.stack.name, this.stack.composeYAML, this.stack.composeENV, this.isAdd, (res) => {
const args = [ this.stack.name, this.stack.composeYAML, this.stack.composeENV, this.isAdd ];
if (this.stack.revision) {
args.push(this.stack.revision);
}
this.saveError = "";
this.$root.emitAgent(this.endpoint, "deployStack", ...args, (res) => {
this.processing = false;
this.$root.toastRes(res);
if (res.ok) {
this.isEditMode = false;
this.captureSavedConfig();
this.$router.push(this.url);
} else {
this.saveError = res.msg || "editorSaveFailed";
}
});
},
saveStack() {
async saveStack() {
if (!this.isEditMode || this.processing || this.hasConfigErrors || (!this.isAdd && !this.dirty)) {
return;
}
this.processing = true;
this.$root.emitAgent(this.stack.endpoint, "saveStack", this.stack.name, this.stack.composeYAML, this.stack.composeENV, this.isAdd, (res) => {
this.processing = false;
this.$root.toastRes(res);
this.saveError = "";
const isAdd = this.isAdd;
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.isEditMode = false;
this.$router.push(this.url);
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;
}
},
startStack() {
@ -686,6 +754,9 @@ export default {
},
discardStack() {
if (this.dirty && !confirm(this.$t("confirmLeaveStack"))) {
return;
}
this.loadStack();
this.isEditMode = false;
},
@ -697,6 +768,9 @@ export default {
}
const config = doc.toJS() ?? {};
if (typeof config !== "object" || Array.isArray(config)) {
throw new Error(this.$t("editorYamlMapping"));
}
// Check data types
// "services" must be an object
@ -718,26 +792,47 @@ export default {
try {
let { config, doc } = this.yamlToJSON(this.stack.composeYAML);
this.yamlDoc = doc;
this.jsonConfig = config;
let env = dotenv.parse(this.stack.composeENV);
let envYAML = envsubstYAML(this.stack.composeYAML, env);
this.envsubstJSONConfig = this.yamlToJSON(envYAML).config;
clearTimeout(yamlErrorTimeout);
this.updatingFromYaml = true;
this.yamlDoc = markRaw(doc);
this.yamlError = "";
this.jsonConfig = config;
this.updateEnvironmentPreview();
} catch (e) {
clearTimeout(yamlErrorTimeout);
this.yamlError = e.message;
} finally {
this.updatingFromYaml = false;
}
},
if (this.yamlError) {
this.yamlError = e.message;
/** Refresh interpolation without rewriting either source file. */
updateEnvironmentPreview() {
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;
} catch {
this.envsubstJSONConfig = {};
}
},
} 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 = "";
}
},
@ -746,11 +841,13 @@ export default {
},
checkYAML() {
return !this.hasConfigErrors;
},
addContainer() {
this.checkYAML();
if (!this.checkYAML()) {
return;
}
if (this.jsonConfig.services[this.newContainerName]) {
this.$root.toastError("Container name already exists");
@ -777,6 +874,44 @@ export default {
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>

View File

@ -7,9 +7,22 @@
<div v-else class="alert alert-warning shadow-box" role="alert">
<h4 class="alert-heading">{{ $t("Console is not enabled") }}</h4>
<p v-html="$t('ConsoleNotEnabledMSG1')"></p>
<p v-html="$t('ConsoleNotEnabledMSG2')"></p>
<p v-html="$t('ConsoleNotEnabledMSG3')"></p>
<i18n-t keypath="ConsoleNotEnabledMSG1" tag="p">
<template #docker><code>{{ $t('dockerCode') }}</code></template>
<template #rm><code>{{ $t('rmCode') }}</code></template>
</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>
</transition>
@ -37,7 +50,7 @@ export default {
});
},
methods: {
}
};
</script>

View File

@ -1,7 +1,7 @@
<template>
<transition name="slide-fade" appear>
<div>
<h1 class="mb-3">{{$t("terminal")}} - {{ serviceName }} ({{ stackName }})</h1>
<h1 class="mb-3">{{ $t("terminal") }} - {{ serviceName }} ({{ stackName }})</h1>
<div class="mb-3">
<router-link :to="sh" class="btn btn-normal me-2">{{ $t("Switch to sh") }}</router-link>

View File

@ -1,11 +1,32 @@
<template>
<div class="container-fluid">
<div class="row">
<div v-if="!$root.isMobile" class="col-12 col-md-4 col-xl-3">
<div>
<router-link to="/compose" class="btn btn-primary mb-3"><font-awesome-icon icon="plus" /> {{ $t("compose") }}</router-link>
</div>
<StackList :scrollbar="true" />
<div v-if="desktop" class="col-md-4 col-xl-3">
<StackList class="stack-navigation stack-nav-sidebar" />
</div>
<div v-else class="col-12 mb-3 stack-navigation">
<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 ref="container" class="col-12 col-md-8 col-xl-9 mb-3">
@ -17,20 +38,52 @@
</template>
<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)");
export default {
components: {
DialogBackdrop,
DialogCloseTrigger,
DialogContent,
DialogPositioner,
DialogRoot,
DialogTitle,
DialogTrigger,
StackList,
},
data() {
return {
height: 0
height: 0,
desktop: desktopViewport.matches,
stackListOpen: false,
};
},
watch: {
"$route.fullPath"() {
this.stackListOpen = false;
},
},
mounted() {
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>

View File

@ -40,7 +40,7 @@
<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>
<div v-for="(agent, endpoint) in $root.agentList" :key="endpoint" class="mb-3 agent">
<div v-for="(agentItem, endpoint) in $root.agentList" :key="endpoint" class="mb-3 agent">
<!-- Agent Status -->
<template v-if="$root.agentStatusList[endpoint]">
<span v-if="$root.agentStatusList[endpoint] === 'online'" class="badge bg-primary me-2">{{ $t("agentOnline") }}</span>
@ -49,15 +49,27 @@
</template>
<!-- Agent Display Name -->
<span v-if="endpoint === ''">{{ $t("currentEndpoint") }}</span>
<a v-else :href="agent.url" target="_blank">{{ endpoint }}</a>
<template v-if="$root.agentStatusList[endpoint]">
<span v-if="endpoint === '' && agentItem.name === ''" class="badge bg-secondary me-2">Current</span>
<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 -->
<font-awesome-icon v-if="endpoint !== ''" class="ms-2 remove-agent" icon="trash" @click="showRemoveAgentDialog[agent.url] = !showRemoveAgentDialog[agent.url]" />
<font-awesome-icon v-if="endpoint !== ''" class="ms-2 remove-agent" icon="trash" @click="showRemoveAgentDialog[agentItem.url] = !showRemoveAgentDialog[agentItem.url]" />
<!-- Remoe Agent Dialog -->
<BModal v-model="showRemoveAgentDialog[agent.url]" :okTitle="$t('removeAgent')" okVariant="danger" @ok="removeAgent(agent.url)">
<p>{{ agent.url }}</p>
<!-- Remove Agent Dialog -->
<BModal v-model="showRemoveAgentDialog[agentItem.url]" :okTitle="$t('removeAgent')" okVariant="danger" @ok="removeAgent(agentItem.url)">
<p>{{ agentItem.url }}</p>
{{ $t("removeAgentMsg") }}
</BModal>
</div>
@ -81,6 +93,11 @@
<input id="password" v-model="agent.password" type="password" class="form-control" required autocomplete="new-password">
</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">
<template v-if="connectingAgent">{{ $t("connecting") }}</template>
<template v-else>{{ $t("connect") }}</template>
@ -121,11 +138,14 @@ export default {
dockerRunCommand: "",
showAgentForm: false,
showRemoveAgentDialog: {},
showEditAgentNameDialog: {},
connectingAgent: false,
agent: {
url: "http://",
username: "",
password: "",
name: "",
updatedName: "",
}
};
},
@ -199,6 +219,19 @@ 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) {
let num = 0;
@ -286,7 +319,7 @@ export default {
}
},
},
}
};
</script>

View File

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

View File

@ -382,18 +382,6 @@ optgroup {
color: $dark-font-color;
}
.stack-list {
.item {
&:hover {
background-color: $dark-bg2;
}
&.active {
background-color: $dark-bg2;
}
}
}
@media (max-width: 550px) {
.table-shadow-box {
tbody {
@ -478,46 +466,6 @@ optgroup {
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 {
color: #122f21;
background-color: $primary;

View File

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

2943
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -59,13 +59,20 @@
},
"devDependencies": {
"@actions/github": "^6.0.0",
"@ark-ui/vue": "~5.40.0",
"@codemirror/commands": "6.10.1",
"@codemirror/lang-python": "^6.1.7",
"@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",
"@fortawesome/fontawesome-svg-core": "6.4.2",
"@fortawesome/free-regular-svg-icons": "6.4.2",
"@fortawesome/free-solid-svg-icons": "6.4.2",
"@fortawesome/vue-fontawesome": "3.0.3",
"@pandacss/dev": "~2.5.0",
"@types/bcryptjs": "^2.4.6",
"@types/bootstrap": "~5.2.10",
"@types/command-exists": "~1.2.3",

38
panda.config.ts Normal file
View File

@ -0,0 +1,38 @@
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",
});