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
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
This commit is contained in:
parent
0329dabb50
commit
720eade8b5
@ -126,6 +126,10 @@ export class AgentManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
connect(url : string, username : string, password : string) {
|
connect(url : string, username : string, password : string) {
|
||||||
|
if (!this.socket.connected) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
let obj = new URL(url);
|
let obj = new URL(url);
|
||||||
let endpoint = obj.host;
|
let endpoint = obj.host;
|
||||||
|
|
||||||
|
|||||||
@ -8,10 +8,27 @@ export class DockerSocketHandler extends AgentSocketHandler {
|
|||||||
create(socket : DockgeSocket, server : DockgeServer, agentSocket : AgentSocket) {
|
create(socket : DockgeSocket, server : DockgeServer, agentSocket : AgentSocket) {
|
||||||
// Do not call super.create()
|
// Do not call super.create()
|
||||||
|
|
||||||
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 {
|
try {
|
||||||
checkLogin(socket);
|
const stack = await this.saveStack(server, name, composeYAML, composeENV, isAdd, revision);
|
||||||
const stack = await this.saveStack(server, name, composeYAML, composeENV, isAdd);
|
|
||||||
await stack.deploy(socket);
|
await stack.deploy(socket);
|
||||||
server.sendStackList();
|
server.sendStackList();
|
||||||
callbackResult({
|
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 {
|
try {
|
||||||
checkLogin(socket);
|
const stack = await this.saveStack(server, name, composeYAML, composeENV, isAdd, revision);
|
||||||
await this.saveStack(server, name, composeYAML, composeENV, isAdd);
|
|
||||||
callbackResult({
|
callbackResult({
|
||||||
ok: true,
|
ok: true,
|
||||||
msg: "Saved",
|
msg: "Saved",
|
||||||
msgi18n: true,
|
msgi18n: true,
|
||||||
|
revision: stack.revision,
|
||||||
}, callback);
|
}, callback);
|
||||||
server.sendStackList();
|
server.sendStackList();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@ -40,9 +59,8 @@ export class DockerSocketHandler extends AgentSocketHandler {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
agentSocket.on("deleteStack", async (name : unknown, callback) => {
|
onStackMutation("deleteStack", async (name : unknown, callback) => {
|
||||||
try {
|
try {
|
||||||
checkLogin(socket);
|
|
||||||
if (typeof(name) !== "string") {
|
if (typeof(name) !== "string") {
|
||||||
throw new ValidationError("Name must be a string");
|
throw new ValidationError("Name must be a string");
|
||||||
}
|
}
|
||||||
@ -55,6 +73,7 @@ export class DockerSocketHandler extends AgentSocketHandler {
|
|||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
server.imageVulnerabilityScan.forget(name);
|
||||||
server.sendStackList();
|
server.sendStackList();
|
||||||
callbackResult({
|
callbackResult({
|
||||||
ok: true,
|
ok: true,
|
||||||
@ -84,12 +103,61 @@ export class DockerSocketHandler extends AgentSocketHandler {
|
|||||||
callbackResult({
|
callbackResult({
|
||||||
ok: true,
|
ok: true,
|
||||||
stack: await stack.toJSON(socket.endpoint),
|
stack: await stack.toJSON(socket.endpoint),
|
||||||
|
autoUpdate: await server.stackAutoUpdate.getPolicy(stack),
|
||||||
|
imageScanSupported: stack.isManagedByDockge,
|
||||||
}, callback);
|
}, callback);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
callbackError(e, callback);
|
callbackError(e, callback);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
agentSocket.on("startStackImageScan", async (name, callback) => {
|
||||||
|
try {
|
||||||
|
checkLogin(socket);
|
||||||
|
if (typeof name !== "string" || !/^[a-z0-9_-]+$/.test(name)
|
||||||
|
|| !await Stack.composeFileExists(server.stacksDir, name)) {
|
||||||
|
throw new ValidationError("imageScanDiscoveryFailed");
|
||||||
|
}
|
||||||
|
const stack = await Stack.getStack(server, name);
|
||||||
|
callbackResult({
|
||||||
|
ok: true,
|
||||||
|
report: server.imageVulnerabilityScan.start(stack),
|
||||||
|
}, callback);
|
||||||
|
} catch (error) {
|
||||||
|
callbackError(error, callback);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
agentSocket.on("getStackImageScan", async (name, callback) => {
|
||||||
|
try {
|
||||||
|
checkLogin(socket);
|
||||||
|
if (typeof name !== "string" || !/^[a-z0-9_-]+$/.test(name)) {
|
||||||
|
throw new ValidationError("imageScanInvalidRequest");
|
||||||
|
}
|
||||||
|
callbackResult({
|
||||||
|
ok: true,
|
||||||
|
report: server.imageVulnerabilityScan.summary(name),
|
||||||
|
}, callback);
|
||||||
|
} catch (error) {
|
||||||
|
callbackError(error, callback);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
agentSocket.on("getStackImageFindings", async (name, reportId, imageId, severity, offset, callback) => {
|
||||||
|
try {
|
||||||
|
checkLogin(socket);
|
||||||
|
if (typeof name !== "string" || !/^[a-z0-9_-]+$/.test(name)) {
|
||||||
|
throw new ValidationError("imageScanInvalidRequest");
|
||||||
|
}
|
||||||
|
callbackResult({
|
||||||
|
ok: true,
|
||||||
|
...server.imageVulnerabilityScan.page(name, reportId, imageId, severity, offset),
|
||||||
|
}, callback);
|
||||||
|
} catch (error) {
|
||||||
|
callbackError(error, callback);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// requestStackList
|
// requestStackList
|
||||||
agentSocket.on("requestStackList", async (callback) => {
|
agentSocket.on("requestStackList", async (callback) => {
|
||||||
try {
|
try {
|
||||||
@ -106,9 +174,8 @@ export class DockerSocketHandler extends AgentSocketHandler {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// startStack
|
// startStack
|
||||||
agentSocket.on("startStack", async (stackName : unknown, callback) => {
|
onStackMutation("startStack", async (stackName : unknown, callback) => {
|
||||||
try {
|
try {
|
||||||
checkLogin(socket);
|
|
||||||
|
|
||||||
if (typeof(stackName) !== "string") {
|
if (typeof(stackName) !== "string") {
|
||||||
throw new ValidationError("Stack name must be a string");
|
throw new ValidationError("Stack name must be a string");
|
||||||
@ -131,9 +198,8 @@ export class DockerSocketHandler extends AgentSocketHandler {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// stopStack
|
// stopStack
|
||||||
agentSocket.on("stopStack", async (stackName : unknown, callback) => {
|
onStackMutation("stopStack", async (stackName : unknown, callback) => {
|
||||||
try {
|
try {
|
||||||
checkLogin(socket);
|
|
||||||
|
|
||||||
if (typeof(stackName) !== "string") {
|
if (typeof(stackName) !== "string") {
|
||||||
throw new ValidationError("Stack name must be a string");
|
throw new ValidationError("Stack name must be a string");
|
||||||
@ -155,9 +221,8 @@ export class DockerSocketHandler extends AgentSocketHandler {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// restartStack
|
// restartStack
|
||||||
agentSocket.on("restartStack", async (stackName : unknown, callback) => {
|
onStackMutation("restartStack", async (stackName : unknown, callback) => {
|
||||||
try {
|
try {
|
||||||
checkLogin(socket);
|
|
||||||
|
|
||||||
if (typeof(stackName) !== "string") {
|
if (typeof(stackName) !== "string") {
|
||||||
throw new ValidationError("Stack name must be a string");
|
throw new ValidationError("Stack name must be a string");
|
||||||
@ -177,9 +242,8 @@ export class DockerSocketHandler extends AgentSocketHandler {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// updateStack
|
// updateStack
|
||||||
agentSocket.on("updateStack", async (stackName : unknown, callback) => {
|
onStackMutation("updateStack", async (stackName : unknown, callback) => {
|
||||||
try {
|
try {
|
||||||
checkLogin(socket);
|
|
||||||
|
|
||||||
if (typeof(stackName) !== "string") {
|
if (typeof(stackName) !== "string") {
|
||||||
throw new ValidationError("Stack name must be a string");
|
throw new ValidationError("Stack name must be a string");
|
||||||
@ -199,9 +263,20 @@ export class DockerSocketHandler extends AgentSocketHandler {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// down stack
|
// 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 {
|
try {
|
||||||
checkLogin(socket);
|
|
||||||
|
|
||||||
if (typeof(stackName) !== "string") {
|
if (typeof(stackName) !== "string") {
|
||||||
throw new ValidationError("Stack name must be a string");
|
throw new ValidationError("Stack name must be a string");
|
||||||
@ -257,9 +332,8 @@ export class DockerSocketHandler extends AgentSocketHandler {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Start a service
|
// Start a service
|
||||||
agentSocket.on("startService", async (stackName: unknown, serviceName: unknown, callback) => {
|
onStackMutation("startService", async (stackName: unknown, serviceName: unknown, callback) => {
|
||||||
try {
|
try {
|
||||||
checkLogin(socket);
|
|
||||||
|
|
||||||
if (typeof (stackName) !== "string" || typeof (serviceName) !== "string") {
|
if (typeof (stackName) !== "string" || typeof (serviceName) !== "string") {
|
||||||
throw new ValidationError("Stack name and service name must be strings");
|
throw new ValidationError("Stack name and service name must be strings");
|
||||||
@ -279,9 +353,8 @@ export class DockerSocketHandler extends AgentSocketHandler {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Stop a service
|
// Stop a service
|
||||||
agentSocket.on("stopService", async (stackName: unknown, serviceName: unknown, callback) => {
|
onStackMutation("stopService", async (stackName: unknown, serviceName: unknown, callback) => {
|
||||||
try {
|
try {
|
||||||
checkLogin(socket);
|
|
||||||
|
|
||||||
if (typeof (stackName) !== "string" || typeof (serviceName) !== "string") {
|
if (typeof (stackName) !== "string" || typeof (serviceName) !== "string") {
|
||||||
throw new ValidationError("Stack name and service name must be strings");
|
throw new ValidationError("Stack name and service name must be strings");
|
||||||
@ -299,9 +372,8 @@ export class DockerSocketHandler extends AgentSocketHandler {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
agentSocket.on("restartService", async (stackName: unknown, serviceName: unknown, callback) => {
|
onStackMutation("restartService", async (stackName: unknown, serviceName: unknown, callback) => {
|
||||||
try {
|
try {
|
||||||
checkLogin(socket);
|
|
||||||
|
|
||||||
if (typeof stackName !== "string" || typeof serviceName !== "string") {
|
if (typeof stackName !== "string" || typeof serviceName !== "string") {
|
||||||
throw new Error("Invalid stackName or serviceName");
|
throw new Error("Invalid stackName or serviceName");
|
||||||
@ -333,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
|
// Check types
|
||||||
if (typeof(name) !== "string") {
|
if (typeof(name) !== "string") {
|
||||||
throw new ValidationError("Name must be a string");
|
throw new ValidationError("Name must be a string");
|
||||||
@ -347,9 +419,12 @@ export class DockerSocketHandler extends AgentSocketHandler {
|
|||||||
if (typeof(isAdd) !== "boolean") {
|
if (typeof(isAdd) !== "boolean") {
|
||||||
throw new ValidationError("isAdd must be a boolean");
|
throw new ValidationError("isAdd must be a boolean");
|
||||||
}
|
}
|
||||||
|
if (revision !== undefined && (typeof revision !== "string" || !/^[a-f0-9]{64}$/.test(revision))) {
|
||||||
|
throw new ValidationError("editorConflict");
|
||||||
|
}
|
||||||
|
|
||||||
const stack = new Stack(server, name, composeYAML, composeENV, false);
|
const stack = new Stack(server, name, composeYAML, composeENV, false);
|
||||||
await stack.save(isAdd);
|
await stack.save(isAdd, revision as string | undefined);
|
||||||
return stack;
|
return stack;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
87
backend/auth-session.ts
Normal file
87
backend/auth-session.ts
Normal 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();
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -37,6 +37,8 @@ import { AgentSocketHandler } from "./agent-socket-handler";
|
|||||||
import { AgentSocket } from "../common/agent-socket";
|
import { AgentSocket } from "../common/agent-socket";
|
||||||
import { ManageAgentSocketHandler } from "./socket-handlers/manage-agent-socket-handler";
|
import { ManageAgentSocketHandler } from "./socket-handlers/manage-agent-socket-handler";
|
||||||
import { Terminal } from "./terminal";
|
import { Terminal } from "./terminal";
|
||||||
|
import { StackAutoUpdate } from "./stack-auto-update";
|
||||||
|
import { ImageVulnerabilityScan } from "./image-vulnerability-scan";
|
||||||
|
|
||||||
export class DockgeServer {
|
export class DockgeServer {
|
||||||
app : Express;
|
app : Express;
|
||||||
@ -78,7 +80,11 @@ export class DockgeServer {
|
|||||||
|
|
||||||
jwtSecret : string = "";
|
jwtSecret : string = "";
|
||||||
|
|
||||||
|
private authModeRevision = 0;
|
||||||
|
|
||||||
stacksDir : string = "";
|
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
|
// Better do anything after added all socket handlers here
|
||||||
// ***************************
|
// ***************************
|
||||||
|
|
||||||
log.debug("auth", "check auto login");
|
|
||||||
if (await Settings.get("disableAuth")) {
|
|
||||||
log.info("auth", "Disabled Auth: auto login to admin");
|
|
||||||
this.afterLogin(dockgeSocket, await R.findOne("user") as User);
|
|
||||||
dockgeSocket.emit("autoLogin");
|
|
||||||
} else {
|
|
||||||
log.debug("auth", "need auth");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Socket disconnect
|
// Socket disconnect
|
||||||
dockgeSocket.on("disconnect", () => {
|
dockgeSocket.on("disconnect", () => {
|
||||||
log.info("server", "Socket disconnected!");
|
log.info("server", "Socket disconnected!");
|
||||||
dockgeSocket.instanceManager.disconnectAll();
|
dockgeSocket.instanceManager.disconnectAll();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const authModeRevision = this.authModeRevision;
|
||||||
|
if (await Settings.get("disableAuth", false)) {
|
||||||
|
const user = await R.findOne("user", "active = 1") as User | null;
|
||||||
|
if (user && dockgeSocket.connected && !dockgeSocket.userID && authModeRevision === this.authModeRevision) {
|
||||||
|
log.info("auth", "Disabled Auth: auto login to admin");
|
||||||
|
this.afterLogin(dockgeSocket, user, true);
|
||||||
|
dockgeSocket.emit("autoLogin");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
||||||
this.io.on("disconnect", () => {
|
this.io.on("disconnect", () => {
|
||||||
@ -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.userID = user.id;
|
||||||
|
socket.authBypassed = authBypassed;
|
||||||
socket.join(user.id.toString());
|
socket.join(user.id.toString());
|
||||||
|
|
||||||
this.sendInfo(socket);
|
this.sendInfo(socket);
|
||||||
@ -404,6 +415,7 @@ export class DockgeServer {
|
|||||||
});
|
});
|
||||||
|
|
||||||
checkVersion.startInterval();
|
checkVersion.startInterval();
|
||||||
|
this.stackAutoUpdate.start();
|
||||||
});
|
});
|
||||||
|
|
||||||
gracefulShutdown(this.httpServer, {
|
gracefulShutdown(this.httpServer, {
|
||||||
@ -411,7 +423,7 @@ export class DockgeServer {
|
|||||||
timeout: 30000, // timeout: 30 secs
|
timeout: 30000, // timeout: 30 secs
|
||||||
development: false, // not in dev mode
|
development: false, // not in dev mode
|
||||||
forceExit: true, // triggers process.exit() at the end of shutdown process
|
forceExit: true, // triggers process.exit() at the end of shutdown process
|
||||||
onShutdown: this.shutdownFunction, // 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
|
finally: this.finalFunction, // finally function (sync) - e.g. for logging
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -681,6 +693,8 @@ export class DockgeServer {
|
|||||||
|
|
||||||
// TODO: Close all terminals?
|
// TODO: Close all terminals?
|
||||||
|
|
||||||
|
this.stackAutoUpdate.stop();
|
||||||
|
await this.imageVulnerabilityScan.stop();
|
||||||
await Database.close();
|
await Database.close();
|
||||||
Settings.stopCacheCleaner();
|
Settings.stopCacheCleaner();
|
||||||
}
|
}
|
||||||
@ -712,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() {
|
isSSL() {
|
||||||
return this.config.sslKey && this.config.sslCert;
|
return this.config.sslKey && this.config.sslCert;
|
||||||
}
|
}
|
||||||
|
|||||||
436
backend/image-vulnerability-scan.ts
Normal file
436
backend/image-vulnerability-scan.ts
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
12
backend/migrations/2026-11-10-0000-revoked-token-table.ts
Normal file
12
backend/migrations/2026-11-10-0000-revoked-token-table.ts
Normal 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");
|
||||||
|
}
|
||||||
@ -1,7 +1,6 @@
|
|||||||
import jwt from "jsonwebtoken";
|
|
||||||
import { R } from "redbean-node";
|
import { R } from "redbean-node";
|
||||||
import { BeanModel } from "redbean-node/dist/bean-model";
|
import { BeanModel } from "redbean-node/dist/bean-model";
|
||||||
import { generatePasswordHash, shake256, SHAKE256_LENGTH } from "../password-hash";
|
import { generatePasswordHash } from "../password-hash";
|
||||||
|
|
||||||
export class User extends BeanModel {
|
export class User extends BeanModel {
|
||||||
/**
|
/**
|
||||||
@ -27,20 +26,6 @@ export class User extends BeanModel {
|
|||||||
await User.resetPassword(this.id, newPassword);
|
await User.resetPassword(this.id, newPassword);
|
||||||
this.password = newPassword;
|
this.password = newPassword;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a new JWT for a user
|
|
||||||
* @param {User} user The User to create a JsonWebToken for
|
|
||||||
* @param {string} jwtSecret The key used to sign the JsonWebToken
|
|
||||||
* @returns {string} the JsonWebToken as a string
|
|
||||||
*/
|
|
||||||
static createJWT(user : User, jwtSecret : string) {
|
|
||||||
return jwt.sign({
|
|
||||||
username: user.username,
|
|
||||||
h: shake256(user.password, SHAKE256_LENGTH),
|
|
||||||
}, jwtSecret);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default User;
|
export default User;
|
||||||
|
|||||||
@ -26,9 +26,10 @@ export class Settings {
|
|||||||
/**
|
/**
|
||||||
* Retrieve value of setting based on key
|
* Retrieve value of setting based on key
|
||||||
* @param key Key of setting to retrieve
|
* @param key Key of setting to retrieve
|
||||||
|
* @param useCache Whether to read and populate the settings cache
|
||||||
* @returns Value
|
* @returns Value
|
||||||
*/
|
*/
|
||||||
static async get(key : string) {
|
static async get(key : string, useCache = true) {
|
||||||
|
|
||||||
// Start cache clear if not started yet
|
// Start cache clear if not started yet
|
||||||
if (!Settings.cacheCleaner) {
|
if (!Settings.cacheCleaner) {
|
||||||
@ -45,7 +46,7 @@ export class Settings {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Query from cache
|
// Query from cache
|
||||||
if (key in Settings.cacheList) {
|
if (useCache && key in Settings.cacheList) {
|
||||||
const v = Settings.cacheList[key].value;
|
const v = Settings.cacheList[key].value;
|
||||||
log.debug("settings", `Get Setting (cache): ${key}: ${v}`);
|
log.debug("settings", `Get Setting (cache): ${key}: ${v}`);
|
||||||
return v;
|
return v;
|
||||||
@ -59,10 +60,12 @@ export class Settings {
|
|||||||
const v = JSON.parse(value);
|
const v = JSON.parse(value);
|
||||||
log.debug("settings", `Get Setting: ${key}: ${v}`);
|
log.debug("settings", `Get Setting: ${key}: ${v}`);
|
||||||
|
|
||||||
Settings.cacheList[key] = {
|
if (useCache) {
|
||||||
value: v,
|
Settings.cacheList[key] = {
|
||||||
timestamp: Date.now()
|
value: v,
|
||||||
};
|
timestamp: Date.now()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
return v;
|
return v;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
import { SocketHandler } from "../socket-handler.js";
|
import { SocketHandler } from "../socket-handler.js";
|
||||||
import { DockgeServer } from "../dockge-server";
|
import { DockgeServer } from "../dockge-server";
|
||||||
import { log } from "../log";
|
import { log } from "../log";
|
||||||
import { checkLogin, DockgeSocket } from "../util-server";
|
import { callbackError, checkLogin, DockgeSocket } from "../util-server";
|
||||||
import { AgentSocket } from "../../common/agent-socket";
|
import { AgentSocket } from "../../common/agent-socket";
|
||||||
import { ALL_ENDPOINTS } from "../../common/util-common";
|
import { ALL_ENDPOINTS } from "../../common/util-common";
|
||||||
|
|
||||||
@ -37,6 +37,10 @@ export class AgentProxySocketHandler extends SocketHandler {
|
|||||||
if (e instanceof Error) {
|
if (e instanceof Error) {
|
||||||
log.warn("agent", e.message);
|
log.warn("agent", e.message);
|
||||||
}
|
}
|
||||||
|
const callback = args.at(-1);
|
||||||
|
if (typeof callback === "function") {
|
||||||
|
callbackError(e, callback);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -12,11 +12,10 @@ import {
|
|||||||
checkLogin,
|
checkLogin,
|
||||||
DockgeSocket,
|
DockgeSocket,
|
||||||
doubleCheckPassword,
|
doubleCheckPassword,
|
||||||
JWTDecoded,
|
|
||||||
ValidationError
|
ValidationError
|
||||||
} from "../util-server";
|
} from "../util-server";
|
||||||
import { passwordStrength } from "check-password-strength";
|
import { passwordStrength } from "check-password-strength";
|
||||||
import jwt from "jsonwebtoken";
|
import { isSessionRevoked, issueSession, revokeSession, verifySession, withSession } from "../auth-session";
|
||||||
import { Settings } from "../settings";
|
import { Settings } from "../settings";
|
||||||
import fs, { promises as fsAsync } from "fs";
|
import fs, { promises as fsAsync } from "fs";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
@ -64,44 +63,47 @@ export class MainSocketHandler extends SocketHandler {
|
|||||||
|
|
||||||
// Login by token
|
// Login by token
|
||||||
socket.on("loginByToken", async (token, callback) => {
|
socket.on("loginByToken", async (token, callback) => {
|
||||||
|
if (typeof callback !== "function") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
const clientIP = await server.getClientIP(socket);
|
const clientIP = await server.getClientIP(socket);
|
||||||
|
|
||||||
log.info("auth", `Login by token. IP=${clientIP}`);
|
log.info("auth", `Login by token. IP=${clientIP}`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const 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 ", [
|
await withSession(session, async () => {
|
||||||
decoded.username,
|
if (await isSessionRevoked(session)) {
|
||||||
]) as User;
|
throw new Error("Session token has been revoked");
|
||||||
|
}
|
||||||
if (user) {
|
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
|
// 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");
|
throw new Error("The token is invalid due to password change or old token");
|
||||||
}
|
}
|
||||||
|
if (session.expiresAt <= Math.floor(Date.now() / 1000)) {
|
||||||
log.debug("auth", "afterLogin");
|
throw new Error("Session token has expired");
|
||||||
|
}
|
||||||
|
if (!socket.connected) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
socket.authSession = session;
|
||||||
await server.afterLogin(socket, user);
|
await server.afterLogin(socket, user);
|
||||||
log.debug("auth", "afterLogin ok");
|
log.info("auth", `Successfully logged in user ${username}. IP=${clientIP}`);
|
||||||
|
callback({ ok: true });
|
||||||
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,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (!(error instanceof Error)) {
|
if (!(error instanceof Error)) {
|
||||||
console.error("Unknown error:", error);
|
console.error("Unknown error:", error);
|
||||||
@ -145,14 +147,13 @@ export class MainSocketHandler extends SocketHandler {
|
|||||||
|
|
||||||
if (user) {
|
if (user) {
|
||||||
if (user.twofa_status === 0) {
|
if (user.twofa_status === 0) {
|
||||||
server.afterLogin(socket, user);
|
|
||||||
|
|
||||||
log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`);
|
log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`);
|
||||||
|
|
||||||
callback({
|
callback({
|
||||||
ok: true,
|
ok: true,
|
||||||
token: User.createJWT(user, server.jwtSecret),
|
token: this.startSession(socket, server, user),
|
||||||
});
|
});
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (user.twofa_status === 1 && !data.token) {
|
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);
|
const verify = notp.totp.verify(data.token, user.twofa_secret, twoFAVerifyOptions);
|
||||||
|
|
||||||
if (user.twofa_last_token !== data.token && verify) {
|
if (user.twofa_last_token !== data.token && verify) {
|
||||||
server.afterLogin(socket, user);
|
|
||||||
|
|
||||||
await R.exec("UPDATE `user` SET twofa_last_token = ? WHERE id = ? ", [
|
await R.exec("UPDATE `user` SET twofa_last_token = ? WHERE id = ? ", [
|
||||||
data.token,
|
data.token,
|
||||||
socket.userID,
|
user.id,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`);
|
log.info("auth", `Successfully logged in user ${data.username}. IP=${clientIP}`);
|
||||||
|
|
||||||
callback({
|
callback({
|
||||||
ok: true,
|
ok: true,
|
||||||
token: User.createJWT(user, server.jwtSecret),
|
token: this.startSession(socket, server, user),
|
||||||
});
|
});
|
||||||
} else {
|
} 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
|
// Change Password
|
||||||
socket.on("changePassword", async (password, callback) => {
|
socket.on("changePassword", async (password, callback) => {
|
||||||
try {
|
try {
|
||||||
@ -266,17 +291,27 @@ export class MainSocketHandler extends SocketHandler {
|
|||||||
});
|
});
|
||||||
|
|
||||||
socket.on("setSettings", async (data, currentPassword, callback) => {
|
socket.on("setSettings", async (data, currentPassword, callback) => {
|
||||||
|
if (typeof callback !== "function") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
checkLogin(socket);
|
checkLogin(socket);
|
||||||
|
|
||||||
// If currently is disabled auth, don't need to check
|
let disableAuth = data.disableAuth;
|
||||||
// Disabled Auth + Want to Disable Auth => No Check
|
if (Object.hasOwn(data, "disableAuth") && typeof disableAuth !== "boolean") {
|
||||||
// Disabled Auth + Want to Enable Auth => No Check
|
throw new ValidationError("Invalid authentication setting.");
|
||||||
// Enabled Auth + Want to Disable Auth => Check!!
|
}
|
||||||
// Enabled Auth + Want to Enable Auth => No Check
|
delete data.disableAuth;
|
||||||
const currentDisabledAuth = await Settings.get("disableAuth");
|
if (disableAuth === true) {
|
||||||
if (!currentDisabledAuth && data.disableAuth) {
|
if (await Settings.get("disableAuth", false)) {
|
||||||
await doubleCheckPassword(socket, currentPassword);
|
// 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
|
// Handle global.env
|
||||||
if (data.globalENV && data.globalENV != "# VARIABLE=value #comment") {
|
if (data.globalENV && data.globalENV != "# VARIABLE=value #comment") {
|
||||||
@ -291,12 +326,24 @@ export class MainSocketHandler extends SocketHandler {
|
|||||||
|
|
||||||
await Settings.setSettings("general", data);
|
await Settings.setSettings("general", data);
|
||||||
|
|
||||||
|
if (typeof disableAuth === "boolean") {
|
||||||
|
if (!socket.connected) {
|
||||||
|
throw new Error("You are not logged in.");
|
||||||
|
}
|
||||||
|
await Settings.set("disableAuth", disableAuth, "general");
|
||||||
|
}
|
||||||
|
|
||||||
callback({
|
callback({
|
||||||
ok: true,
|
ok: true,
|
||||||
msg: "Saved"
|
msg: "Saved"
|
||||||
});
|
});
|
||||||
|
|
||||||
server.sendInfo(socket);
|
if (disableAuth === false) {
|
||||||
|
server.revokeBypassedSessions();
|
||||||
|
}
|
||||||
|
if (socket.connected) {
|
||||||
|
server.sendInfo(socket);
|
||||||
|
}
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e instanceof Error) {
|
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> {
|
async login(username : string, password : string) : Promise<User | null> {
|
||||||
if (typeof username !== "string" || typeof password !== "string") {
|
if (typeof username !== "string" || typeof password !== "string") {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
337
backend/stack-auto-update.ts
Normal file
337
backend/stack-auto-update.ts
Normal 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
109
backend/stack-files.ts
Normal 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
105
backend/stack.ts
105
backend/stack.ts
@ -1,5 +1,6 @@
|
|||||||
import { DockgeServer } from "./dockge-server";
|
import { DockgeServer } from "./dockge-server";
|
||||||
import fs, { promises as fsAsync } from "fs";
|
import fs, { promises as fsAsync } from "fs";
|
||||||
|
import { createHash } from "node:crypto";
|
||||||
import { log } from "./log";
|
import { log } from "./log";
|
||||||
import yaml from "yaml";
|
import yaml from "yaml";
|
||||||
import { DockgeSocket, fileExists, ValidationError } from "./util-server";
|
import { DockgeSocket, fileExists, ValidationError } from "./util-server";
|
||||||
@ -19,6 +20,8 @@ import {
|
|||||||
import { InteractiveTerminal, Terminal } from "./terminal";
|
import { InteractiveTerminal, Terminal } from "./terminal";
|
||||||
import childProcessAsync from "promisify-child-process";
|
import childProcessAsync from "promisify-child-process";
|
||||||
import { Settings } from "./settings";
|
import { Settings } from "./settings";
|
||||||
|
import { analyzeEnv } from "../common/env-file";
|
||||||
|
import { saveStackFiles } from "./stack-files";
|
||||||
|
|
||||||
export class Stack {
|
export class Stack {
|
||||||
|
|
||||||
@ -33,6 +36,27 @@ export class Stack {
|
|||||||
protected combinedTerminal? : Terminal;
|
protected combinedTerminal? : Terminal;
|
||||||
|
|
||||||
protected static managedStackList: Map<string, Stack> = new Map();
|
protected static managedStackList: Map<string, Stack> = new Map();
|
||||||
|
private static operations = new Set<string>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hold the stack lock across filesystem changes and all Compose steps.
|
||||||
|
* @param server Dockge instance that owns the stack
|
||||||
|
* @param name Stack directory name
|
||||||
|
* @param action Operation to run
|
||||||
|
* @returns The operation result
|
||||||
|
*/
|
||||||
|
static async withOperation<T>(server: DockgeServer, name: string, action: () => Promise<T>): Promise<T> {
|
||||||
|
const directory = path.resolve(server.stacksDir, name);
|
||||||
|
if (this.operations.has(directory)) {
|
||||||
|
throw new ValidationError("Another operation is already running, please try again later.");
|
||||||
|
}
|
||||||
|
this.operations.add(directory);
|
||||||
|
try {
|
||||||
|
return await action();
|
||||||
|
} finally {
|
||||||
|
this.operations.delete(directory);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
constructor(server : DockgeServer, name : string, composeYAML? : string, composeENV? : string, skipFSOperations = false) {
|
constructor(server : DockgeServer, name : string, composeYAML? : string, composeENV? : string, skipFSOperations = false) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
@ -75,6 +99,7 @@ export class Stack {
|
|||||||
composeYAML: this.composeYAML,
|
composeYAML: this.composeYAML,
|
||||||
composeENV: this.composeENV,
|
composeENV: this.composeENV,
|
||||||
primaryHostname,
|
primaryHostname,
|
||||||
|
revision: this.revision,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -111,6 +136,10 @@ export class Stack {
|
|||||||
return this._status;
|
return this._status;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get revision(): string {
|
||||||
|
return createHash("sha256").update(JSON.stringify([ this._composeFileName, this.composeYAML, this.composeENV ])).digest("hex");
|
||||||
|
}
|
||||||
|
|
||||||
validate() {
|
validate() {
|
||||||
// Check name, allows [a-z][0-9] _ - only
|
// Check name, allows [a-z][0-9] _ - only
|
||||||
if (!this.name.match(/^[a-z0-9_-]+$/)) {
|
if (!this.name.match(/^[a-z0-9_-]+$/)) {
|
||||||
@ -118,15 +147,15 @@ export class Stack {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check YAML format
|
// Check YAML format
|
||||||
yaml.parse(this.composeYAML);
|
const config = yaml.parse(this.composeYAML);
|
||||||
|
if (config !== null && (typeof config !== "object" || Array.isArray(config))) {
|
||||||
let lines = this.composeENV.split("\n");
|
throw new ValidationError("editorYamlMapping");
|
||||||
|
}
|
||||||
// Check if the .env is able to pass docker-compose
|
if (config?.services && (typeof config.services !== "object" || Array.isArray(config.services))) {
|
||||||
// Prevent "setenv: The parameter is incorrect"
|
throw new ValidationError("editorServicesMapping");
|
||||||
// It only happens when there is one line and it doesn't contain "="
|
}
|
||||||
if (lines.length === 1 && !lines[0].includes("=") && lines[0].length > 0) {
|
if (analyzeEnv(this.composeENV).some(issue => issue.severity === "error")) {
|
||||||
throw new ValidationError("Invalid .env format");
|
throw new ValidationError("editorInvalidEnv");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -174,11 +203,32 @@ export class Stack {
|
|||||||
/**
|
/**
|
||||||
* Save the stack to the disk
|
* Save the stack to the disk
|
||||||
* @param isAdd
|
* @param isAdd
|
||||||
|
* @param expectedRevision Version loaded by the editor, omitted by legacy clients
|
||||||
*/
|
*/
|
||||||
async save(isAdd : boolean) {
|
async save(isAdd : boolean, expectedRevision?: string) {
|
||||||
this.validate();
|
this.validate();
|
||||||
|
|
||||||
let dir = this.path;
|
let dir = this.path;
|
||||||
|
let owner;
|
||||||
|
if (process.env.PUID && process.env.PGID) {
|
||||||
|
const uid = Number(process.env.PUID);
|
||||||
|
const gid = Number(process.env.PGID);
|
||||||
|
if (!Number.isSafeInteger(uid) || uid < 0 || !Number.isSafeInteger(gid) || gid < 0) {
|
||||||
|
throw new ValidationError("Invalid PUID or PGID");
|
||||||
|
}
|
||||||
|
owner = {
|
||||||
|
uid,
|
||||||
|
gid,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const checkRevision = () => {
|
||||||
|
if (!isAdd && expectedRevision !== undefined) {
|
||||||
|
const current = new Stack(this.server, this.name);
|
||||||
|
if (current.revision !== expectedRevision && current.revision !== this.revision) {
|
||||||
|
throw new ValidationError("editorConflict");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// Check if the name is used if isAdd
|
// Check if the name is used if isAdd
|
||||||
if (isAdd) {
|
if (isAdd) {
|
||||||
@ -192,21 +242,40 @@ export class Stack {
|
|||||||
if (!await fileExists(dir)) {
|
if (!await fileExists(dir)) {
|
||||||
throw new ValidationError("Stack not found");
|
throw new ValidationError("Stack not found");
|
||||||
}
|
}
|
||||||
|
checkRevision();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write or overwrite the compose.yaml
|
try {
|
||||||
fs.writeFileSync(path.join(dir, this._composeFileName), this.composeYAML);
|
if (owner) {
|
||||||
if (process.env.PUID && process.env.PGID) {
|
await fsAsync.lchown(dir, owner.uid, owner.gid);
|
||||||
const uid = Number(process.env.PUID);
|
}
|
||||||
const gid = Number(process.env.PGID);
|
await saveStackFiles([
|
||||||
fs.lchownSync(dir, uid, gid);
|
{
|
||||||
fs.chownSync(path.join(dir, this._composeFileName), uid, gid);
|
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> {
|
async deploy(socket : DockgeSocket) : Promise<number> {
|
||||||
const terminalName = getComposeTerminalName(socket.endpoint, this.name);
|
const terminalName = getComposeTerminalName(socket.endpoint, this.name);
|
||||||
let exitCode = await Terminal.exec(this.server, socket, terminalName, "docker", this.getComposeOptions("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) {
|
if (exitCode !== 0) {
|
||||||
throw new Error("Failed to deploy, please check the terminal output for more information.");
|
throw new Error("Failed to deploy, please check the terminal output for more information.");
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,14 +7,12 @@ import { R } from "redbean-node";
|
|||||||
import { verifyPassword } from "./password-hash";
|
import { verifyPassword } from "./password-hash";
|
||||||
import fs from "fs";
|
import fs from "fs";
|
||||||
import { AgentManager } from "./agent-manager";
|
import { AgentManager } from "./agent-manager";
|
||||||
|
import type { AuthSession } from "./auth-session";
|
||||||
export interface JWTDecoded {
|
|
||||||
username : string;
|
|
||||||
h? : string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface DockgeSocket extends Socket {
|
export interface DockgeSocket extends Socket {
|
||||||
userID: number;
|
userID: number;
|
||||||
|
authBypassed?: boolean;
|
||||||
|
authSession?: AuthSession;
|
||||||
consoleTerminal? : Terminal;
|
consoleTerminal? : Terminal;
|
||||||
instanceManager : AgentManager;
|
instanceManager : AgentManager;
|
||||||
endpoint : string;
|
endpoint : string;
|
||||||
|
|||||||
71
common/env-file.ts
Normal file
71
common/env-file.ts
Normal 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;
|
||||||
|
}
|
||||||
@ -16,12 +16,30 @@ RUN npm ci --omit=dev
|
|||||||
# ⭐ Main Image
|
# ⭐ Main Image
|
||||||
############################################
|
############################################
|
||||||
FROM louislam/dockge:base AS release
|
FROM louislam/dockge:base AS release
|
||||||
|
ARG TARGETARCH
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --chown=node:node --from=build_healthcheck /app/extra/healthcheck /app/extra/healthcheck
|
COPY --chown=node:node --from=build_healthcheck /app/extra/healthcheck /app/extra/healthcheck
|
||||||
COPY --from=build /app/node_modules /app/node_modules
|
COPY --from=build /app/node_modules /app/node_modules
|
||||||
COPY --chown=node:node . .
|
COPY --chown=node:node . .
|
||||||
RUN mkdir ./data
|
RUN mkdir ./data
|
||||||
|
|
||||||
|
# Grype is available upstream for the amd64 and arm64 images.
|
||||||
|
RUN set -eu; \
|
||||||
|
case "$TARGETARCH" in \
|
||||||
|
amd64) checksum=e9da18cc1429e786722e32161288103600efffd8e483c90761f90485bd1bec85 ;; \
|
||||||
|
arm64) checksum=b7815598d48da78bfd16f5b98ef28e1bb09c03d34fc8c3e350f99b6ccb3c7cba ;; \
|
||||||
|
*) echo "Install Grype separately to enable image scans on $TARGETARCH"; exit 0 ;; \
|
||||||
|
esac; \
|
||||||
|
temp_dir="$(mktemp -d)"; \
|
||||||
|
trap 'rm -rf "$temp_dir"' EXIT; \
|
||||||
|
curl --fail --location --retry 3 \
|
||||||
|
"https://github.com/anchore/grype/releases/download/v0.121.3/grype_0.121.3_linux_${TARGETARCH}.tar.gz" \
|
||||||
|
--output "$temp_dir/grype.tar.gz"; \
|
||||||
|
echo "$checksum $temp_dir/grype.tar.gz" | sha256sum --check --status; \
|
||||||
|
tar -xzf "$temp_dir/grype.tar.gz" -C "$temp_dir" grype LICENSE; \
|
||||||
|
install -m 0755 "$temp_dir/grype" /usr/local/bin/grype; \
|
||||||
|
install -D -m 0644 "$temp_dir/LICENSE" /usr/share/doc/grype/LICENSE
|
||||||
|
|
||||||
|
|
||||||
# It is just for safe, as by default, it is disabled in the latest Node.js now.
|
# It is just for safe, as by default, it is disabled in the latest Node.js now.
|
||||||
# Read more:
|
# Read more:
|
||||||
|
|||||||
2
frontend/components.d.ts
vendored
2
frontend/components.d.ts
vendored
@ -23,11 +23,13 @@ declare module 'vue' {
|
|||||||
General: typeof import('./src/components/settings/General.vue')['default']
|
General: typeof import('./src/components/settings/General.vue')['default']
|
||||||
GlobalEnv: typeof import('./src/components/settings/GlobalEnv.vue')['default']
|
GlobalEnv: typeof import('./src/components/settings/GlobalEnv.vue')['default']
|
||||||
HiddenInput: typeof import('./src/components/HiddenInput.vue')['default']
|
HiddenInput: typeof import('./src/components/HiddenInput.vue')['default']
|
||||||
|
ImageVulnerabilities: typeof import('./src/components/ImageVulnerabilities.vue')['default']
|
||||||
Login: typeof import('./src/components/Login.vue')['default']
|
Login: typeof import('./src/components/Login.vue')['default']
|
||||||
NetworkInput: typeof import('./src/components/NetworkInput.vue')['default']
|
NetworkInput: typeof import('./src/components/NetworkInput.vue')['default']
|
||||||
RouterLink: typeof import('vue-router')['RouterLink']
|
RouterLink: typeof import('vue-router')['RouterLink']
|
||||||
RouterView: typeof import('vue-router')['RouterView']
|
RouterView: typeof import('vue-router')['RouterView']
|
||||||
Security: typeof import('./src/components/settings/Security.vue')['default']
|
Security: typeof import('./src/components/settings/Security.vue')['default']
|
||||||
|
StackConfigEditor: typeof import('./src/components/StackConfigEditor.vue')['default']
|
||||||
StackList: typeof import('./src/components/StackList.vue')['default']
|
StackList: typeof import('./src/components/StackList.vue')['default']
|
||||||
StackListItem: typeof import('./src/components/StackListItem.vue')['default']
|
StackListItem: typeof import('./src/components/StackListItem.vue')['default']
|
||||||
Terminal: typeof import('./src/components/Terminal.vue')['default']
|
Terminal: typeof import('./src/components/Terminal.vue')['default']
|
||||||
|
|||||||
370
frontend/src/components/ImageVulnerabilities.vue
Normal file
370
frontend/src/components/ImageVulnerabilities.vue
Normal 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>
|
||||||
@ -51,6 +51,8 @@ export default {
|
|||||||
externalList: {},
|
externalList: {},
|
||||||
selectedExternalList: {},
|
selectedExternalList: {},
|
||||||
externalNetworkList: [],
|
externalNetworkList: [],
|
||||||
|
loadingNetworkList: false,
|
||||||
|
applyingNetworks: false,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
@ -62,10 +64,6 @@ export default {
|
|||||||
return this.$parent.$parent.stack;
|
return this.$parent.$parent.stack;
|
||||||
},
|
},
|
||||||
|
|
||||||
editorFocus() {
|
|
||||||
return this.$parent.$parent.editorFocus;
|
|
||||||
},
|
|
||||||
|
|
||||||
endpoint() {
|
endpoint() {
|
||||||
return this.$parent.$parent.endpoint;
|
return this.$parent.$parent.endpoint;
|
||||||
},
|
},
|
||||||
@ -73,16 +71,19 @@ export default {
|
|||||||
watch: {
|
watch: {
|
||||||
"jsonConfig.networks": {
|
"jsonConfig.networks": {
|
||||||
handler() {
|
handler() {
|
||||||
if (this.editorFocus) {
|
if (!this.applyingNetworks) {
|
||||||
console.debug("jsonConfig.networks changed");
|
|
||||||
this.loadNetworkList();
|
this.loadNetworkList();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
deep: true,
|
deep: true,
|
||||||
|
flush: "sync",
|
||||||
},
|
},
|
||||||
|
|
||||||
"selectedExternalList": {
|
"selectedExternalList": {
|
||||||
handler() {
|
handler() {
|
||||||
|
if (this.loadingNetworkList) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
for (const networkName in this.selectedExternalList) {
|
for (const networkName in this.selectedExternalList) {
|
||||||
const enable = this.selectedExternalList[networkName];
|
const enable = this.selectedExternalList[networkName];
|
||||||
|
|
||||||
@ -98,13 +99,17 @@ export default {
|
|||||||
this.applyToYAML();
|
this.applyToYAML();
|
||||||
},
|
},
|
||||||
deep: true,
|
deep: true,
|
||||||
|
flush: "sync",
|
||||||
},
|
},
|
||||||
|
|
||||||
"networkList": {
|
"networkList": {
|
||||||
handler() {
|
handler() {
|
||||||
this.applyToYAML();
|
if (!this.loadingNetworkList) {
|
||||||
|
this.applyToYAML();
|
||||||
|
}
|
||||||
},
|
},
|
||||||
deep: true,
|
deep: true,
|
||||||
|
flush: "sync",
|
||||||
}
|
}
|
||||||
|
|
||||||
},
|
},
|
||||||
@ -114,6 +119,7 @@ export default {
|
|||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
loadNetworkList() {
|
loadNetworkList() {
|
||||||
|
this.loadingNetworkList = true;
|
||||||
this.networkList = [];
|
this.networkList = [];
|
||||||
this.externalList = {};
|
this.externalList = {};
|
||||||
|
|
||||||
@ -135,6 +141,7 @@ export default {
|
|||||||
for (const networkName in this.externalList) {
|
for (const networkName in this.externalList) {
|
||||||
this.selectedExternalList[networkName] = true;
|
this.selectedExternalList[networkName] = true;
|
||||||
}
|
}
|
||||||
|
this.loadingNetworkList = false;
|
||||||
},
|
},
|
||||||
|
|
||||||
loadExternalNetworkList() {
|
loadExternalNetworkList() {
|
||||||
@ -167,27 +174,28 @@ export default {
|
|||||||
|
|
||||||
remove(index) {
|
remove(index) {
|
||||||
this.networkList.splice(index, 1);
|
this.networkList.splice(index, 1);
|
||||||
this.applyToYAML();
|
|
||||||
},
|
},
|
||||||
|
|
||||||
applyToYAML() {
|
applyToYAML() {
|
||||||
if (this.editorFocus) {
|
if (this.loadingNetworkList) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.jsonConfig.networks = {};
|
const networks = {};
|
||||||
|
|
||||||
// Internal networks
|
// Internal networks
|
||||||
for (const networkRow of this.networkList) {
|
for (const networkRow of this.networkList) {
|
||||||
this.jsonConfig.networks[networkRow.key] = networkRow.value;
|
networks[networkRow.key] = networkRow.value;
|
||||||
}
|
}
|
||||||
|
|
||||||
// External networks
|
// External networks
|
||||||
for (const networkName in this.externalList) {
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
},
|
},
|
||||||
|
|||||||
495
frontend/src/components/StackConfigEditor.vue
Normal file
495
frontend/src/components/StackConfigEditor.vue
Normal 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>
|
||||||
|
|
||||||
@ -1,495 +1,217 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="shadow-box mb-3" :style="boxStyle">
|
<nav class="stack-nav-panel" :aria-label="$t('stackListTitle')">
|
||||||
<div class="list-header">
|
<div class="stack-nav-header">
|
||||||
<div class="header-top">
|
<slot name="title">
|
||||||
<!-- TODO -->
|
<h2 class="stack-nav-title">{{ $t("stackListTitle") }}</h2>
|
||||||
<button
|
</slot>
|
||||||
v-if="false" class="btn btn-outline-normal ms-2" :class="{ 'active': selectMode }" type="button"
|
<router-link to="/compose" class="stack-nav-button stack-nav-primary" @click.left.exact="$emit('navigate')">
|
||||||
@click="selectMode = !selectMode"
|
<font-awesome-icon icon="plus" aria-hidden="true" /> {{ $t("stackListNew") }}
|
||||||
>
|
</router-link>
|
||||||
{{ $t("Select") }}
|
<slot name="close" />
|
||||||
</button>
|
</div>
|
||||||
|
|
||||||
<div class="placeholder"></div>
|
<div class="stack-nav-controls">
|
||||||
<div class="search-wrapper">
|
<label class="stack-nav-field">
|
||||||
<a v-if="searchText == ''" class="search-icon">
|
<span>{{ $t("stackListSearch") }}</span>
|
||||||
<font-awesome-icon icon="search" />
|
<span class="stack-nav-search">
|
||||||
</a>
|
<font-awesome-icon icon="search" aria-hidden="true" />
|
||||||
<a v-if="searchText != ''" class="search-icon" style="cursor: pointer" @click="clearSearchText">
|
<input ref="search" v-model.trim="searchText" type="search" :placeholder="$t('stackListSearchPlaceholder')" autocomplete="off">
|
||||||
<font-awesome-icon icon="times" />
|
|
||||||
</a>
|
|
||||||
<form>
|
|
||||||
<input v-model="searchText" class="form-control search-input" autocomplete="off" />
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- TODO -->
|
|
||||||
<div v-if="false" class="header-filter">
|
|
||||||
<!--<StackListFilter :filterState="filterState" @update-filter="updateFilter" />-->
|
|
||||||
</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>
|
</span>
|
||||||
</div>
|
</label>
|
||||||
</div>
|
<div class="stack-nav-filters">
|
||||||
<div ref="stackList" class="stack-list" :class="{ scrollbar: scrollbar }" :style="stackListStyle">
|
<div class="stack-nav-field">
|
||||||
<div v-if="agentStackList[0] && agentStackList[0].stacks.length === 0" class="text-center mt-3">
|
<label :for="hostId">{{ $t("stackListHost") }}</label>
|
||||||
<router-link to="/compose">{{ $t("addFirstStackMsg") }}</router-link>
|
<select :id="hostId" v-model="host">
|
||||||
</div>
|
<option :value="null">{{ $t("stackListAllHosts") }}</option>
|
||||||
<div v-for="(agent, agentIndex) in agentStackList" :key="agentIndex" class="stack-list-inner">
|
<option v-for="agent in agents" :key="agent.endpoint" :value="agent.endpoint">
|
||||||
<div
|
{{ agent.name }}
|
||||||
v-if="$root.agentCount > 1" class="p-2 agent-select"
|
</option>
|
||||||
@click="closedAgents.set(agent.endpoint, !closedAgents.get(agent.endpoint))"
|
</select>
|
||||||
>
|
</div>
|
||||||
<span class="me-1">
|
<div class="stack-nav-field">
|
||||||
<font-awesome-icon v-show="closedAgents.get(agent.endpoint)" icon="chevron-circle-right" />
|
<label :for="statusId">{{ $t("stackListStatus") }}</label>
|
||||||
<font-awesome-icon v-show="!closedAgents.get(agent.endpoint)" icon="chevron-circle-down" />
|
<select :id="statusId" v-model="status">
|
||||||
</span>
|
<option value="">{{ $t("stackListAllStatuses") }}</option>
|
||||||
<span v-if="agent.endpoint === 'current'">{{ $t("currentEndpoint") }}</span>
|
<option v-for="option in statuses" :key="option" :value="option">
|
||||||
<span v-else>{{ agent.endpoint }}</span>
|
{{ $t(option) }}
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<StackListItem
|
|
||||||
v-for="(item, index) in agent.stacks"
|
|
||||||
v-show="$root.agentCount === 1 || !closedAgents.get(agent.endpoint)" :key="index" :stack="item" :isSelectMode="selectMode"
|
|
||||||
:isSelected="isSelected" :select="select" :deselect="deselect"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<Confirm ref="confirmPause" :yes-text="$t('Yes')" :no-text="$t('No')" @yes="pauseSelected">
|
<div class="stack-nav-summary">
|
||||||
{{ $t("pauseStackMsg") }}
|
<span role="status">{{ loading ? $t("stackListLoading") : $t("stackListCount", resultCount) }}</span>
|
||||||
</Confirm>
|
<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>
|
||||||
|
<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>
|
||||||
|
</nav>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
import Confirm from "../components/Confirm.vue";
|
import { CollapsibleContent, CollapsibleRoot, CollapsibleTrigger } from "@ark-ui/vue/collapsible";
|
||||||
import StackListItem from "../components/StackListItem.vue";
|
import { useId } from "vue";
|
||||||
import { CREATED_FILE, CREATED_STACK, EXITED, RUNNING, UNKNOWN } from "../../../common/util-common";
|
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 {
|
export default {
|
||||||
components: {
|
components: {
|
||||||
Confirm,
|
CollapsibleContent,
|
||||||
|
CollapsibleRoot,
|
||||||
|
CollapsibleTrigger,
|
||||||
StackListItem,
|
StackListItem,
|
||||||
},
|
},
|
||||||
props: {
|
emits: [ "navigate" ],
|
||||||
/** Should the scrollbar be shown */
|
setup() {
|
||||||
scrollbar: {
|
return {
|
||||||
type: Boolean,
|
hostId: useId(),
|
||||||
},
|
statusId: useId(),
|
||||||
|
};
|
||||||
},
|
},
|
||||||
data() {
|
data() {
|
||||||
return {
|
return {
|
||||||
searchText: "",
|
searchText: "",
|
||||||
selectMode: false,
|
host: null,
|
||||||
selectAll: false,
|
status: "",
|
||||||
disableSelectAllWatcher: false,
|
statuses,
|
||||||
selectedStacks: {},
|
|
||||||
windowTop: 0,
|
|
||||||
filterState: {
|
|
||||||
status: null,
|
|
||||||
active: null,
|
|
||||||
tags: null,
|
|
||||||
},
|
|
||||||
closedAgents: new Map(),
|
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
/**
|
agents() {
|
||||||
* Improve the sticky appearance of the list by increasing its
|
const agents = new Map();
|
||||||
* height as user scrolls down.
|
const endpoints = [ "", ...Object.keys(this.$root.agentList).filter(Boolean) ];
|
||||||
* Not used on mobile.
|
|
||||||
* @returns {object} Style for stack list
|
for (const endpoint of endpoints) {
|
||||||
*/
|
agents.set(endpoint, this.describeAgent(endpoint));
|
||||||
boxStyle() {
|
}
|
||||||
if (window.innerWidth > 550) {
|
for (const stack of Object.values(this.$root.completeStackList)) {
|
||||||
return {
|
const endpoint = stack.endpoint || "";
|
||||||
height: `calc(100vh - 160px + ${this.windowTop}px)`,
|
if (!agents.has(endpoint)) {
|
||||||
};
|
agents.set(endpoint, this.describeAgent(endpoint));
|
||||||
} else {
|
}
|
||||||
return {
|
agents.get(endpoint).stacks.push(stack);
|
||||||
height: "calc(100vh - 160px)",
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const [ local, ...remote ] = agents.values();
|
||||||
|
remote.sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
return [ local, ...remote ];
|
||||||
},
|
},
|
||||||
|
filteredAgents() {
|
||||||
/**
|
const query = this.searchText.toLowerCase();
|
||||||
* Returns a sorted list of stacks based on the applied filters and search text.
|
return this.agents.filter(agent => this.host === null || agent.endpoint === this.host).map(agent => {
|
||||||
* @returns {Array} The sorted list of stacks.
|
const stacks = agent.stacks.filter(stack => {
|
||||||
*/
|
const status = statusNameShort(stack.status);
|
||||||
agentStackList() {
|
if (this.status && (status === "?" ? "stackListUnknown" : status) !== this.status) {
|
||||||
let result = Object.values(this.$root.completeStackList);
|
return false;
|
||||||
|
|
||||||
result = result.filter(stack => {
|
|
||||||
// filter by search text
|
|
||||||
// finds stack name, tag name or tag value
|
|
||||||
let searchTextMatch = true;
|
|
||||||
if (this.searchText !== "") {
|
|
||||||
const loweredSearchText = this.searchText.toLowerCase();
|
|
||||||
searchTextMatch =
|
|
||||||
stack.name.toLowerCase().includes(loweredSearchText)
|
|
||||||
|| stack.tags.find(tag => tag.name.toLowerCase().includes(loweredSearchText)
|
|
||||||
|| tag.value?.toLowerCase().includes(loweredSearchText));
|
|
||||||
}
|
|
||||||
|
|
||||||
// filter by active
|
|
||||||
let activeMatch = true;
|
|
||||||
if (this.filterState.active != null && this.filterState.active.length > 0) {
|
|
||||||
activeMatch = this.filterState.active.includes(stack.active);
|
|
||||||
}
|
|
||||||
|
|
||||||
// filter by tags
|
|
||||||
let tagsMatch = true;
|
|
||||||
if (this.filterState.tags != null && this.filterState.tags.length > 0) {
|
|
||||||
tagsMatch = stack.tags.map(tag => tag.tag_id) // convert to array of tag IDs
|
|
||||||
.filter(stackTagId => this.filterState.tags.includes(stackTagId)) // perform Array Intersaction between filter and stack's tags
|
|
||||||
.length > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
return searchTextMatch && activeMatch && tagsMatch;
|
|
||||||
});
|
|
||||||
|
|
||||||
result.sort((m1, m2) => {
|
|
||||||
|
|
||||||
// sort by managed by dockge
|
|
||||||
if (m1.isManagedByDockge && !m2.isManagedByDockge) {
|
|
||||||
return -1;
|
|
||||||
} else if (!m1.isManagedByDockge && m2.isManagedByDockge) {
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// sort by status
|
|
||||||
if (m1.status !== m2.status) {
|
|
||||||
if (m2.status === RUNNING) {
|
|
||||||
return 1;
|
|
||||||
} else if (m1.status === RUNNING) {
|
|
||||||
return -1;
|
|
||||||
} else if (m2.status === EXITED) {
|
|
||||||
return 1;
|
|
||||||
} else if (m1.status === EXITED) {
|
|
||||||
return -1;
|
|
||||||
} else if (m2.status === CREATED_STACK) {
|
|
||||||
return 1;
|
|
||||||
} else if (m1.status === CREATED_STACK) {
|
|
||||||
return -1;
|
|
||||||
} else if (m2.status === CREATED_FILE) {
|
|
||||||
return 1;
|
|
||||||
} else if (m1.status === CREATED_FILE) {
|
|
||||||
return -1;
|
|
||||||
} else if (m2.status === UNKNOWN) {
|
|
||||||
return 1;
|
|
||||||
} else if (m1.status === UNKNOWN) {
|
|
||||||
return -1;
|
|
||||||
}
|
}
|
||||||
}
|
return !query || stack.name.toLowerCase().includes(query)
|
||||||
return m1.name.localeCompare(m2.name);
|
|| 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 };
|
||||||
});
|
});
|
||||||
|
|
||||||
// Group stacks by endpoint, sorting them so the local endpoint is first
|
|
||||||
// and the rest are sorted alphabetically
|
|
||||||
result = [
|
|
||||||
...result.reduce((acc, stack) => {
|
|
||||||
const endpoint = stack.endpoint || "current";
|
|
||||||
if (!acc.has(endpoint)) {
|
|
||||||
acc.set(endpoint, []);
|
|
||||||
}
|
|
||||||
acc.get(endpoint).push(stack);
|
|
||||||
return acc;
|
|
||||||
}, new Map()).entries()
|
|
||||||
].map(([ endpoint, stacks ]) => ({
|
|
||||||
endpoint,
|
|
||||||
stacks
|
|
||||||
})).sort((a, b) => {
|
|
||||||
if (a.endpoint === "current" && b.endpoint !== "current") {
|
|
||||||
return -1;
|
|
||||||
} else if (a.endpoint !== "current" && b.endpoint === "current") {
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
return a.endpoint.localeCompare(b.endpoint);
|
|
||||||
});
|
|
||||||
|
|
||||||
return result;
|
|
||||||
},
|
},
|
||||||
|
visibleAgents() {
|
||||||
isDarkTheme() {
|
return this.filteredAgents.filter(agent => agent.stacks.length || agent.connection !== "online");
|
||||||
return document.body.classList.contains("dark");
|
|
||||||
},
|
},
|
||||||
|
resultCount() {
|
||||||
stackListStyle() {
|
return this.filteredAgents.reduce((total, agent) => total + agent.stacks.length, 0);
|
||||||
//let listHeaderHeight = 107;
|
|
||||||
let listHeaderHeight = 60;
|
|
||||||
|
|
||||||
if (this.selectMode) {
|
|
||||||
listHeaderHeight += 42;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
"height": `calc(100% - ${listHeaderHeight}px)`
|
|
||||||
};
|
|
||||||
},
|
},
|
||||||
|
loading() {
|
||||||
selectedStackCount() {
|
return this.filteredAgents.some(agent => agent.connection !== "offline" && !agent.loaded);
|
||||||
return Object.keys(this.selectedStacks).length;
|
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
|
||||||
* Determines if any filters are active.
|
|
||||||
* @returns {boolean} True if any filter is active, false otherwise.
|
|
||||||
*/
|
|
||||||
filtersActive() {
|
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: {
|
watch: {
|
||||||
searchText() {
|
agents(agents) {
|
||||||
for (let stack of this.agentStackList) {
|
if (this.host !== null && !agents.some(agent => agent.endpoint === this.host)) {
|
||||||
if (!this.selectedStacks[stack.id]) {
|
this.host = null;
|
||||||
if (this.selectAll) {
|
|
||||||
this.disableSelectAllWatcher = true;
|
|
||||||
this.selectAll = false;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
selectAll() {
|
|
||||||
if (!this.disableSelectAllWatcher) {
|
|
||||||
this.selectedStacks = {};
|
|
||||||
|
|
||||||
if (this.selectAll) {
|
|
||||||
this.agentStackList.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: {
|
methods: {
|
||||||
/**
|
/**
|
||||||
* Handle user scroll
|
* Build the label and connection state for an agent, including agents without stacks.
|
||||||
* @returns {void}
|
* @param {string} endpoint Agent endpoint, or an empty string for the local host
|
||||||
|
* @returns {object} Agent shown in the stack navigator
|
||||||
*/
|
*/
|
||||||
onScroll() {
|
describeAgent(endpoint) {
|
||||||
if (window.top.scrollY <= 133) {
|
const loaded = endpoint ? Object.hasOwn(this.$root.allAgentStackList, endpoint) : this.$root.stackListLoaded;
|
||||||
this.windowTop = window.top.scrollY;
|
return {
|
||||||
} else {
|
endpoint,
|
||||||
this.windowTop = 133;
|
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}
|
* @returns {void}
|
||||||
*/
|
*/
|
||||||
clearSearchText() {
|
clearFilters() {
|
||||||
this.searchText = "";
|
this.searchText = "";
|
||||||
},
|
this.host = null;
|
||||||
/**
|
this.status = "";
|
||||||
* Update the StackList Filter
|
this.$refs.search.focus();
|
||||||
* @param {object} newFilter Object with new filter
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
updateFilter(newFilter) {
|
|
||||||
this.filterState = newFilter;
|
|
||||||
},
|
|
||||||
/**
|
|
||||||
* Deselect a stack
|
|
||||||
* @param {number} id ID of stack
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
deselect(id) {
|
|
||||||
delete this.selectedStacks[id];
|
|
||||||
},
|
|
||||||
/**
|
|
||||||
* Select a stack
|
|
||||||
* @param {number} id ID of stack
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
select(id) {
|
|
||||||
this.selectedStacks[id] = true;
|
|
||||||
},
|
|
||||||
/**
|
|
||||||
* Determine if stack is selected
|
|
||||||
* @param {number} id ID of stack
|
|
||||||
* @returns {bool} Is the stack selected?
|
|
||||||
*/
|
|
||||||
isSelected(id) {
|
|
||||||
return id in this.selectedStacks;
|
|
||||||
},
|
|
||||||
/**
|
|
||||||
* Disable select mode and reset selection
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
cancelSelectMode() {
|
|
||||||
this.selectMode = false;
|
|
||||||
this.selectedStacks = {};
|
|
||||||
},
|
|
||||||
/**
|
|
||||||
* Show dialog to confirm pause
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
pauseDialog() {
|
|
||||||
this.$refs.confirmPause.show();
|
|
||||||
},
|
|
||||||
/**
|
|
||||||
* Pause each selected stack
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
pauseSelected() {
|
|
||||||
Object.keys(this.selectedStacks)
|
|
||||||
.filter(id => this.$root.stackList[id].active)
|
|
||||||
.forEach(id => this.$root.getSocket().emit("pauseStack", id, () => { }));
|
|
||||||
|
|
||||||
this.cancelSelectMode();
|
|
||||||
},
|
|
||||||
/**
|
|
||||||
* Resume each selected stack
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
resumeSelected() {
|
|
||||||
Object.keys(this.selectedStacks)
|
|
||||||
.filter(id => !this.$root.stackList[id].active)
|
|
||||||
.forEach(id => this.$root.getSocket().emit("resumeStack", id, () => { }));
|
|
||||||
|
|
||||||
this.cancelSelectMode();
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style lang="scss" scoped>
|
|
||||||
@import "../styles/vars.scss";
|
|
||||||
|
|
||||||
.shadow-box {
|
|
||||||
height: calc(100vh - 150px);
|
|
||||||
position: sticky;
|
|
||||||
top: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.small-padding {
|
|
||||||
padding-left: 5px !important;
|
|
||||||
padding-right: 5px !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.list-header {
|
|
||||||
border-bottom: 1px solid #dee2e6;
|
|
||||||
border-radius: 10px 10px 0 0;
|
|
||||||
margin: -10px;
|
|
||||||
margin-bottom: 10px;
|
|
||||||
padding: 10px;
|
|
||||||
|
|
||||||
.dark & {
|
|
||||||
background-color: $dark-header-bg;
|
|
||||||
border-bottom: 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.header-top {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.header-filter {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 770px) {
|
|
||||||
.list-header {
|
|
||||||
margin: -20px;
|
|
||||||
margin-bottom: 10px;
|
|
||||||
padding: 5px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-wrapper {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-icon {
|
|
||||||
padding: 10px;
|
|
||||||
color: #c0c0c0;
|
|
||||||
|
|
||||||
// Clear filter button (X)
|
|
||||||
svg[data-icon="times"] {
|
|
||||||
cursor: pointer;
|
|
||||||
transition: all ease-in-out 0.1s;
|
|
||||||
|
|
||||||
&:hover {
|
|
||||||
opacity: 0.5;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.search-input {
|
|
||||||
max-width: 15em;
|
|
||||||
}
|
|
||||||
|
|
||||||
.stack-item {
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.tags {
|
|
||||||
margin-top: 4px;
|
|
||||||
padding-left: 67px;
|
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.bottom-style {
|
|
||||||
padding-left: 67px;
|
|
||||||
margin-top: 5px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.selection-controls {
|
|
||||||
margin-top: 5px;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.agent-select {
|
|
||||||
cursor: pointer;
|
|
||||||
font-size: 14px;
|
|
||||||
font-weight: 500;
|
|
||||||
color: $dark-font-color3;
|
|
||||||
padding-left: 10px;
|
|
||||||
padding-right: 10px;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
user-select: none;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
|
|||||||
@ -1,180 +1,43 @@
|
|||||||
<template>
|
<template>
|
||||||
<router-link :to="url" :class="{ 'dim' : !stack.isManagedByDockge }" class="item">
|
<router-link :to="url" class="stack-nav-item" @click.left.exact="$emit('navigate')">
|
||||||
<Uptime :stack="stack" :fixed-width="true" class="me-2" />
|
<span class="stack-nav-item-copy">
|
||||||
<div class="title">
|
<span class="stack-nav-name">{{ stack.name }}</span>
|
||||||
<span>{{ stackName }}</span>
|
<span class="stack-nav-item-meta">
|
||||||
</div>
|
{{ hostName }}<template v-if="!stack.isManagedByDockge"> · {{ $t("stackListUnmanaged") }}</template>
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
<span class="stack-nav-badge" :data-state="status">
|
||||||
|
{{ $t(status) }}
|
||||||
|
</span>
|
||||||
</router-link>
|
</router-link>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
import Uptime from "./Uptime.vue";
|
import { statusNameShort } from "../../../common/util-common";
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
components: {
|
|
||||||
Uptime
|
|
||||||
},
|
|
||||||
props: {
|
props: {
|
||||||
/** Stack this represents */
|
/** Stack to link to */
|
||||||
stack: {
|
stack: {
|
||||||
type: Object,
|
type: Object,
|
||||||
default: null,
|
required: true,
|
||||||
},
|
},
|
||||||
/** If the user is in select mode */
|
/** Display name of the host running the stack */
|
||||||
isSelectMode: {
|
hostName: {
|
||||||
type: Boolean,
|
type: String,
|
||||||
default: false,
|
required: true,
|
||||||
},
|
|
||||||
/** 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: () => {}
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
data() {
|
emits: [ "navigate" ],
|
||||||
return {
|
|
||||||
isCollapsed: true,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
computed: {
|
computed: {
|
||||||
endpointDisplay() {
|
status() {
|
||||||
return this.$root.endpointDisplayFunction(this.stack.endpoint);
|
const status = statusNameShort(this.stack.status);
|
||||||
|
return status === "?" ? "stackListUnknown" : status;
|
||||||
},
|
},
|
||||||
url() {
|
url() {
|
||||||
if (this.stack.endpoint) {
|
const name = encodeURIComponent(this.stack.name);
|
||||||
return `/compose/${this.stack.name}/${this.stack.endpoint}`;
|
return this.stack.endpoint ? `/compose/${name}/${encodeURIComponent(this.stack.endpoint)}` : `/compose/${name}`;
|
||||||
} else {
|
|
||||||
return `/compose/${this.stack.name}`;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
depthMargin() {
|
|
||||||
return {
|
|
||||||
marginLeft: `${31 * this.depth}px`,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
stackName() {
|
|
||||||
return this.stack.name;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
watch: {
|
|
||||||
isSelectMode() {
|
|
||||||
// TODO: Resize the heartbeat bar, but too slow
|
|
||||||
// this.$refs.heartbeatBar.resize();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
beforeMount() {
|
|
||||||
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
/**
|
|
||||||
* Changes the collapsed value of the current stack and saves
|
|
||||||
* it to local storage
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
changeCollapsed() {
|
|
||||||
this.isCollapsed = !this.isCollapsed;
|
|
||||||
|
|
||||||
// Save collapsed value into local storage
|
|
||||||
let storage = window.localStorage.getItem("stackCollapsed");
|
|
||||||
let storageObject = {};
|
|
||||||
if (storage !== null) {
|
|
||||||
storageObject = JSON.parse(storage);
|
|
||||||
}
|
|
||||||
storageObject[`stack_${this.stack.id}`] = this.isCollapsed;
|
|
||||||
|
|
||||||
window.localStorage.setItem("stackCollapsed", JSON.stringify(storageObject));
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Toggle selection of stack
|
|
||||||
* @returns {void}
|
|
||||||
*/
|
|
||||||
toggleSelection() {
|
|
||||||
if (this.isSelected(this.stack.id)) {
|
|
||||||
this.deselect(this.stack.id);
|
|
||||||
} else {
|
|
||||||
this.select(this.stack.id);
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style lang="scss" scoped>
|
|
||||||
@import "../styles/vars.scss";
|
|
||||||
|
|
||||||
.small-padding {
|
|
||||||
padding-left: 5px !important;
|
|
||||||
padding-right: 5px !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.collapse-padding {
|
|
||||||
padding-left: 8px !important;
|
|
||||||
padding-right: 2px !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.item {
|
|
||||||
text-decoration: none;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
min-height: 52px;
|
|
||||||
border-radius: 10px;
|
|
||||||
transition: all ease-in-out 0.15s;
|
|
||||||
width: 100%;
|
|
||||||
padding: 5px 8px;
|
|
||||||
&.disabled {
|
|
||||||
opacity: 0.3;
|
|
||||||
}
|
|
||||||
&:hover {
|
|
||||||
background-color: $highlight-white;
|
|
||||||
}
|
|
||||||
&.active {
|
|
||||||
background-color: #cdf8f4;
|
|
||||||
}
|
|
||||||
.title {
|
|
||||||
margin-top: -4px;
|
|
||||||
}
|
|
||||||
.endpoint {
|
|
||||||
font-size: 12px;
|
|
||||||
color: $dark-font-color3;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.collapsed {
|
|
||||||
transform: rotate(-90deg);
|
|
||||||
}
|
|
||||||
|
|
||||||
.animated {
|
|
||||||
transition: all 0.2s $easing-in;
|
|
||||||
}
|
|
||||||
|
|
||||||
.select-input-wrapper {
|
|
||||||
float: left;
|
|
||||||
margin-top: 15px;
|
|
||||||
margin-left: 3px;
|
|
||||||
margin-right: 10px;
|
|
||||||
padding-left: 4px;
|
|
||||||
position: relative;
|
|
||||||
z-index: 15;
|
|
||||||
}
|
|
||||||
|
|
||||||
.dim {
|
|
||||||
opacity: 0.5;
|
|
||||||
}
|
|
||||||
|
|
||||||
</style>
|
|
||||||
|
|||||||
@ -184,23 +184,23 @@ export default {
|
|||||||
|
|
||||||
/** Disable authentication for web app access */
|
/** Disable authentication for web app access */
|
||||||
disableAuth() {
|
disableAuth() {
|
||||||
this.settings.disableAuth = true;
|
|
||||||
|
|
||||||
// Need current password to disable auth
|
// Need current password to disable auth
|
||||||
// Set it to empty if done
|
// Set it to empty if done
|
||||||
this.saveSettings(() => {
|
this.saveSettings(() => {
|
||||||
this.password.currentPassword = "";
|
this.password.currentPassword = "";
|
||||||
this.$root.username = null;
|
this.$root.username = null;
|
||||||
this.$root.socketIO.token = "autoLogin";
|
}, this.password.currentPassword, true);
|
||||||
}, this.password.currentPassword);
|
|
||||||
},
|
},
|
||||||
|
|
||||||
/** Enable authentication for web app access */
|
/** Enable authentication for web app access */
|
||||||
enableAuth() {
|
enableAuth() {
|
||||||
this.settings.disableAuth = false;
|
this.saveSettings(() => {
|
||||||
this.saveSettings();
|
if (this.$root.socketIO.token === "autoLogin") {
|
||||||
this.$root.storage().removeItem("token");
|
this.$root.finishLogout();
|
||||||
location.reload();
|
} else {
|
||||||
|
this.$root.logout();
|
||||||
|
}
|
||||||
|
}, undefined, false);
|
||||||
},
|
},
|
||||||
|
|
||||||
/** Show confirmation dialog for disable auth */
|
/** Show confirmation dialog for disable auth */
|
||||||
|
|||||||
@ -12,17 +12,125 @@
|
|||||||
"registry": "Registry",
|
"registry": "Registry",
|
||||||
"compose": "Compose",
|
"compose": "Compose",
|
||||||
"addFirstStackMsg": "Compose your first stack!",
|
"addFirstStackMsg": "Compose your first stack!",
|
||||||
|
"stackListTitle": "Stacks",
|
||||||
|
"stackListNew": "New stack",
|
||||||
|
"stackListSearch": "Search stacks",
|
||||||
|
"stackListSearchPlaceholder": "Name or tag",
|
||||||
|
"stackListHost": "Host",
|
||||||
|
"stackListAllHosts": "All hosts",
|
||||||
|
"stackListStatus": "Status",
|
||||||
|
"stackListAllStatuses": "All statuses",
|
||||||
|
"stackListUnknown": "Unknown",
|
||||||
|
"stackListLocal": "Local host",
|
||||||
|
"stackListUnmanaged": "Unmanaged",
|
||||||
|
"stackListEmpty": "No stacks yet.",
|
||||||
|
"stackListHostEmpty": "No stacks on this host.",
|
||||||
|
"stackListNoMatches": "No matching stacks.",
|
||||||
|
"stackListLoading": "Loading stacks…",
|
||||||
|
"stackListStale": "Connection lost. Status may be out of date.",
|
||||||
|
"stackListResetFilters": "Clear filters",
|
||||||
|
"stackListClose": "Close stack list",
|
||||||
|
"stackListCount": "No stacks | 1 stack | {count} stacks",
|
||||||
"stackName": "Stack Name",
|
"stackName": "Stack Name",
|
||||||
"deployStack": "Deploy",
|
"deployStack": "Deploy",
|
||||||
"deleteStack": "Delete",
|
"deleteStack": "Delete",
|
||||||
"stopStack": "Stop",
|
"stopStack": "Stop",
|
||||||
"restartStack": "Restart",
|
"restartStack": "Restart",
|
||||||
"updateStack": "Update",
|
"updateStack": "Update",
|
||||||
|
"autoUpdateTitle": "Automatic image updates",
|
||||||
|
"imageScanTitle": "Image vulnerabilities",
|
||||||
|
"imageScanDescription": "On-demand Grype scan of the images used by this stack's containers. The scan may download vulnerability database updates.",
|
||||||
|
"imageScanStart": "Scan images",
|
||||||
|
"imageScanRefresh": "Refresh scan",
|
||||||
|
"imageScanProgress": "Scanning images · {completed} / {total} finished",
|
||||||
|
"imageScanNotRun": "No scan results available.",
|
||||||
|
"imageScanNoImages": "No images found for this stack's containers.",
|
||||||
|
"imageScanImage": "Image",
|
||||||
|
"imageScanSeverityLabel": "Severity",
|
||||||
|
"imageScanCounts": "Findings by severity",
|
||||||
|
"imageScanAllSeverities": "All severities",
|
||||||
|
"imageScanFindings": "Reported vulnerabilities for the selected image",
|
||||||
|
"imageScanAdvisory": "Advisory",
|
||||||
|
"imageScanPackage": "Package",
|
||||||
|
"imageScanInstalled": "Installed",
|
||||||
|
"imageScanFixed": "Fixed in",
|
||||||
|
"imageScanFixUnknown": "No fix version reported",
|
||||||
|
"imageScanNoFindings": "No findings reported for this filter.",
|
||||||
|
"imageScanLoading": "Loading findings…",
|
||||||
|
"imageScanPrevious": "Previous",
|
||||||
|
"imageScanNext": "Next",
|
||||||
|
"imageScanPage": "{first}–{last} of {total}",
|
||||||
|
"imageScanTimestamp": "Snapshot from {time}",
|
||||||
|
"imageScanDatabase": "Vulnerability database built {time}",
|
||||||
|
"imageScanTruncated": "The 500 highest-severity findings are retained for this image. Counts include all reported findings.",
|
||||||
|
"imageScanRetention": "Results describe the scanned image IDs. Dockge keeps the latest scan for up to eight stacks until it restarts.",
|
||||||
|
"imageScanHostBusy": "Another image scan is running on this host. Try again when it finishes.",
|
||||||
|
"imageScanInvalidRequest": "Invalid image scan request.",
|
||||||
|
"imageScanReportChanged": "This scan result has changed or expired. Refresh the scan view.",
|
||||||
|
"imageScanRequestFailed": "Dockge could not load the scan state. Check the connection and refresh the scan view.",
|
||||||
|
"imageScanFailed": "The image scan failed. Check the Docker connection and scanner configuration.",
|
||||||
|
"imageScanDiscoveryFailed": "Dockge could not identify this stack's local container images.",
|
||||||
|
"imageScanTooManyImages": "A scan supports up to 20 distinct images per stack.",
|
||||||
|
"imageScanImageTooLarge": "This image exceeds the 1 GiB scan size limit.",
|
||||||
|
"imageScanExportFailed": "Docker could not export this image.",
|
||||||
|
"imageScanImageFailed": "The image scan failed or timed out. Check the Grype installation, database access, and available disk space.",
|
||||||
|
"imageScanInvalidReport": "Grype returned an invalid or unsupported report.",
|
||||||
|
"imageScanScannerUnavailable": "Install Grype on this host to enable scanning. New Dockge images include Grype on amd64 and arm64. Native installations can set DOCKGE_GRYPE_PATH to the executable.",
|
||||||
|
"imageScanStatus": {
|
||||||
|
"pending": "Pending",
|
||||||
|
"scanned": "Scanned",
|
||||||
|
"failed": "Failed"
|
||||||
|
},
|
||||||
|
"imageScanSeverity": {
|
||||||
|
"critical": "Critical",
|
||||||
|
"high": "High",
|
||||||
|
"medium": "Medium",
|
||||||
|
"low": "Low",
|
||||||
|
"negligible": "Negligible",
|
||||||
|
"unknown": "Unknown"
|
||||||
|
},
|
||||||
|
"autoUpdateEnable": "Enable automatic updates for this stack",
|
||||||
|
"autoUpdateDescription": "Daily at 04:00 UTC. Dockge can restart running services when their images change. Services with undeployed configuration changes are skipped.",
|
||||||
|
"autoUpdateLastRun": "Last run: {time} · {result}",
|
||||||
|
"autoUpdateSaveFailed": "Dockge could not confirm the automatic update setting. Reopen this stack to check it.",
|
||||||
|
"autoUpdateResult": {
|
||||||
|
"updated": "Image updates applied",
|
||||||
|
"unchanged": "Eligible images up to date",
|
||||||
|
"skipped": "No eligible services",
|
||||||
|
"failed": "Update failed. See the Dockge server logs."
|
||||||
|
},
|
||||||
"startStack": "Start",
|
"startStack": "Start",
|
||||||
"downStack": "Stop & Inactive",
|
"downStack": "Stop & Inactive",
|
||||||
"editStack": "Edit",
|
"editStack": "Edit",
|
||||||
"discardStack": "Discard",
|
"discardStack": "Discard",
|
||||||
"saveStackDraft": "Save",
|
"saveStackDraft": "Save",
|
||||||
|
"editorTitle": "Stack configuration editor",
|
||||||
|
"editorFiles": "Configuration files",
|
||||||
|
"editorFind": "Find",
|
||||||
|
"editorFormat": "Format YAML",
|
||||||
|
"editorWrap": "Line wrap",
|
||||||
|
"editorFullscreen": "Fullscreen",
|
||||||
|
"editorExitFullscreen": "Exit fullscreen",
|
||||||
|
"editorUnsaved": "Unsaved changes",
|
||||||
|
"editorSaved": "Saved",
|
||||||
|
"editorReadOnly": "Read only",
|
||||||
|
"editorCursor": "Ln {line}, Col {column}",
|
||||||
|
"editorLine": "Line {line}",
|
||||||
|
"editorSaveShortcut": "Ctrl/Cmd+S to save",
|
||||||
|
"editorDiagnostics": "Configuration diagnostics",
|
||||||
|
"editorYamlMapping": "The Compose document must be a YAML mapping.",
|
||||||
|
"editorServicesMapping": "Services must be a mapping of service names to settings.",
|
||||||
|
"editorEnvDuplicate": "This variable is defined more than once. Later definitions take precedence.",
|
||||||
|
"editorEnvUnclosedQuote": "This quoted value is not closed.",
|
||||||
|
"editorEnvNull": "An environment file cannot contain a NUL character.",
|
||||||
|
"editorInvalidEnv": "Fix the environment file errors before saving.",
|
||||||
|
"editorConflict": "The configuration changed on the host. Your edits are still here. Discard them to load the saved version, or copy them before reloading.",
|
||||||
|
"editorSaveFailed": "Dockge could not save this configuration.",
|
||||||
|
"editorSaveUnconfirmed": "The host did not confirm the save. Your edits are still here. Retry saving or reload the stack to check the saved version.",
|
||||||
|
"editorComposeInvalid": "Docker Compose validation failed. Check the progress output for details.",
|
||||||
|
"editorFileConflict": "Compose and .env resolve to the same file. Save them to separate files.",
|
||||||
|
"editorFileNotRegular": "The configuration path must point to a regular file.",
|
||||||
|
"editorSaveRecoveryFailed": "Saving failed and automatic recovery was incomplete. Check the .dockge-*.bak files alongside the affected configuration files before retrying.",
|
||||||
"notAvailableShort": "N/A",
|
"notAvailableShort": "N/A",
|
||||||
"deleteStackMsg": "Are you sure you want to delete this stack?",
|
"deleteStackMsg": "Are you sure you want to delete this stack?",
|
||||||
"cancel": "Cancel",
|
"cancel": "Cancel",
|
||||||
@ -82,6 +190,7 @@
|
|||||||
"Password": "Password",
|
"Password": "Password",
|
||||||
"Settings": "Settings",
|
"Settings": "Settings",
|
||||||
"Logout": "Logout",
|
"Logout": "Logout",
|
||||||
|
"authLogoutFailed": "Dockge could not confirm that this session ended. Please try again while connected.",
|
||||||
"Lowercase only": "Lowercase only",
|
"Lowercase only": "Lowercase only",
|
||||||
"Convert to Compose": "Convert to Compose",
|
"Convert to Compose": "Convert to Compose",
|
||||||
"Docker Run": "Docker Run",
|
"Docker Run": "Docker Run",
|
||||||
|
|||||||
@ -13,7 +13,8 @@ export default defineComponent({
|
|||||||
data() {
|
data() {
|
||||||
return {
|
return {
|
||||||
socketIO: {
|
socketIO: {
|
||||||
token: null,
|
token: null as string | null,
|
||||||
|
logoutPending: false,
|
||||||
firstConnect: true,
|
firstConnect: true,
|
||||||
connected: false,
|
connected: false,
|
||||||
connectCount: 0,
|
connectCount: 0,
|
||||||
@ -32,6 +33,7 @@ export default defineComponent({
|
|||||||
composeTemplate: "",
|
composeTemplate: "",
|
||||||
|
|
||||||
stackList: {},
|
stackList: {},
|
||||||
|
stackListLoaded: false,
|
||||||
|
|
||||||
// All stack list from all agents
|
// All stack list from all agents
|
||||||
allAgentStackList: {} as Record<string, object>,
|
allAgentStackList: {} as Record<string, object>,
|
||||||
@ -184,7 +186,7 @@ export default defineComponent({
|
|||||||
this.socketIO.connectCount++;
|
this.socketIO.connectCount++;
|
||||||
this.socketIO.connected = true;
|
this.socketIO.connected = true;
|
||||||
this.socketIO.showReverseProxyGuide = false;
|
this.socketIO.showReverseProxyGuide = false;
|
||||||
const token = this.storage().token;
|
const token = this.socketIO.token ?? this.storage().token;
|
||||||
|
|
||||||
if (token) {
|
if (token) {
|
||||||
if (token !== "autoLogin") {
|
if (token !== "autoLogin") {
|
||||||
@ -253,6 +255,7 @@ export default defineComponent({
|
|||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
if (!res.endpoint) {
|
if (!res.endpoint) {
|
||||||
this.stackList = res.stackList;
|
this.stackList = res.stackList;
|
||||||
|
this.stackListLoaded = true;
|
||||||
} else {
|
} else {
|
||||||
if (!this.allAgentStackList[res.endpoint]) {
|
if (!this.allAgentStackList[res.endpoint]) {
|
||||||
this.allAgentStackList[res.endpoint] = {
|
this.allAgentStackList[res.endpoint] = {
|
||||||
@ -292,6 +295,10 @@ export default defineComponent({
|
|||||||
socket.on("refresh", () => {
|
socket.on("refresh", () => {
|
||||||
location.reload();
|
location.reload();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
socket.on("sessionRevoked", () => {
|
||||||
|
this.finishLogout();
|
||||||
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -311,11 +318,11 @@ export default defineComponent({
|
|||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get payload of JWT cookie
|
* Get the payload of the active session token
|
||||||
* @returns {(object | undefined)} JWT payload
|
* @returns {(object | undefined)} JWT payload
|
||||||
*/
|
*/
|
||||||
getJWTPayload() {
|
getJWTPayload() {
|
||||||
const jwtToken = this.storage().token;
|
const jwtToken = this.socketIO.token;
|
||||||
|
|
||||||
if (jwtToken && jwtToken !== "autoLogin") {
|
if (jwtToken && jwtToken !== "autoLogin") {
|
||||||
return jwtDecode(jwtToken);
|
return jwtDecode(jwtToken);
|
||||||
@ -367,8 +374,9 @@ export default defineComponent({
|
|||||||
this.allowLoginDialog = true;
|
this.allowLoginDialog = true;
|
||||||
|
|
||||||
if (! res.ok) {
|
if (! res.ok) {
|
||||||
this.logout();
|
this.finishLogout(token);
|
||||||
} else {
|
} else {
|
||||||
|
this.socketIO.token = token;
|
||||||
this.loggedIn = true;
|
this.loggedIn = true;
|
||||||
this.username = this.getJWTPayload()?.username;
|
this.username = this.getJWTPayload()?.username;
|
||||||
this.afterLogin();
|
this.afterLogin();
|
||||||
@ -377,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}
|
* @returns {void}
|
||||||
*/
|
*/
|
||||||
logout() {
|
finishLogout(token = this.socketIO.token) {
|
||||||
socket.emit("logout", () => { });
|
socket.disconnect();
|
||||||
this.storage().removeItem("token");
|
for (const storage of [ localStorage, sessionStorage ]) {
|
||||||
|
if (storage.getItem("token") === token) {
|
||||||
|
storage.removeItem("token");
|
||||||
|
}
|
||||||
|
}
|
||||||
this.socketIO.token = null;
|
this.socketIO.token = null;
|
||||||
this.loggedIn = false;
|
this.loggedIn = false;
|
||||||
this.username = null;
|
this.username = null;
|
||||||
this.clearData();
|
this.clearData();
|
||||||
|
location.reload();
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @returns {void}
|
* @returns {void}
|
||||||
*/
|
*/
|
||||||
clearData() {
|
clearData() {
|
||||||
|
this.stackListLoaded = false;
|
||||||
},
|
},
|
||||||
|
|
||||||
afterLogin() {
|
afterLogin() {
|
||||||
|
|||||||
@ -11,12 +11,12 @@
|
|||||||
|
|
||||||
<div v-if="stack.isManagedByDockge" class="mb-3">
|
<div v-if="stack.isManagedByDockge" class="mb-3">
|
||||||
<div class="btn-group me-2" role="group">
|
<div class="btn-group me-2" role="group">
|
||||||
<button v-if="isEditMode" class="btn btn-primary" :disabled="processing" @click="deployStack">
|
<button v-if="isEditMode" class="btn btn-primary" :disabled="processing || hasConfigErrors" @click="deployStack">
|
||||||
<font-awesome-icon icon="rocket" class="me-1" />
|
<font-awesome-icon icon="rocket" class="me-1" />
|
||||||
{{ $t("deployStack") }}
|
{{ $t("deployStack") }}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<button v-if="isEditMode" class="btn btn-normal" :disabled="processing" @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" />
|
<font-awesome-icon icon="save" class="me-1" />
|
||||||
{{ $t("saveStackDraft") }}
|
{{ $t("saveStackDraft") }}
|
||||||
</button>
|
</button>
|
||||||
@ -61,6 +61,29 @@
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<p v-if="saveError" class="alert alert-danger" role="alert">{{ $t(saveError) }}</p>
|
||||||
|
|
||||||
|
<section v-if="!isAdd && !isEditMode && autoUpdate" class="shadow-box mb-3" aria-labelledby="auto-update-heading">
|
||||||
|
<h2 id="auto-update-heading" class="h6 mb-2">{{ $t("autoUpdateTitle") }}</h2>
|
||||||
|
<div class="form-check form-switch mb-1">
|
||||||
|
<input
|
||||||
|
id="auto-update-toggle" class="form-check-input" type="checkbox" role="switch"
|
||||||
|
:checked="autoUpdate.enabled" :disabled="processing || autoUpdateSaving"
|
||||||
|
aria-describedby="auto-update-description" @change="setAutoUpdate"
|
||||||
|
>
|
||||||
|
<label for="auto-update-toggle" class="form-check-label">{{ $t("autoUpdateEnable") }}</label>
|
||||||
|
</div>
|
||||||
|
<p id="auto-update-description" class="small mb-0">{{ $t("autoUpdateDescription") }}</p>
|
||||||
|
<p v-if="autoUpdate.lastRun" class="small mt-2 mb-0">
|
||||||
|
{{ $t("autoUpdateLastRun", {
|
||||||
|
time: new Date(autoUpdate.lastRun.at).toLocaleString($i18n.locale),
|
||||||
|
result: $t("autoUpdateResult." + autoUpdate.lastRun.result),
|
||||||
|
}) }}
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<ImageVulnerabilities v-if="!isAdd && !isEditMode && imageScanSupported" :stack-name="stack.name" :endpoint="endpoint" />
|
||||||
|
|
||||||
<!-- URLs -->
|
<!-- URLs -->
|
||||||
<div v-if="urls.length > 0" class="mb-3">
|
<div v-if="urls.length > 0" class="mb-3">
|
||||||
<a v-for="(urlItem, index) in urls" :key="index" target="_blank" :href="urlItem.url">
|
<a v-for="(urlItem, index) in urls" :key="index" target="_blank" :href="urlItem.url">
|
||||||
@ -81,7 +104,7 @@
|
|||||||
></Terminal>
|
></Terminal>
|
||||||
</transition>
|
</transition>
|
||||||
|
|
||||||
<div v-if="stack.isManagedByDockge" class="row">
|
<fieldset v-if="stack.isManagedByDockge" class="row" :disabled="processing">
|
||||||
<div class="col-lg-6">
|
<div class="col-lg-6">
|
||||||
<!-- General -->
|
<!-- General -->
|
||||||
<div v-if="isAdd">
|
<div v-if="isAdd">
|
||||||
@ -167,45 +190,13 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-lg-6">
|
<div class="col-lg-6">
|
||||||
<h4 class="mb-3">{{ stack.composeFileName }}</h4>
|
<StackConfigEditor
|
||||||
|
v-if="!processing || stack.composeYAML !== undefined"
|
||||||
<!-- YAML editor -->
|
v-model:yaml="stack.composeYAML" v-model:env="stack.composeENV"
|
||||||
<div class="shadow-box mb-3 editor-box" :class="{'edit-mode' : isEditMode}">
|
class="mb-3" :file-name="stack.composeFileName || 'compose.yaml'"
|
||||||
<code-mirror
|
:editable="isEditMode" :disabled="processing" :dirty="dirty"
|
||||||
ref="editor"
|
@save="saveStack"
|
||||||
v-model="stack.composeYAML"
|
/>
|
||||||
:extensions="extensions"
|
|
||||||
minimal
|
|
||||||
wrap="true"
|
|
||||||
dark="true"
|
|
||||||
tab="true"
|
|
||||||
:disabled="!isEditMode"
|
|
||||||
:hasFocus="editorFocus"
|
|
||||||
@change="yamlCodeChange"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div v-if="isEditMode" class="mb-3">
|
|
||||||
{{ yamlError }}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- ENV editor -->
|
|
||||||
<div v-if="isEditMode">
|
|
||||||
<h4 class="mb-3">.env</h4>
|
|
||||||
<div class="shadow-box mb-3 editor-box" :class="{'edit-mode' : isEditMode}">
|
|
||||||
<code-mirror
|
|
||||||
ref="editor"
|
|
||||||
v-model="stack.composeENV"
|
|
||||||
:extensions="extensionsEnv"
|
|
||||||
minimal
|
|
||||||
wrap="true"
|
|
||||||
dark="true"
|
|
||||||
tab="true"
|
|
||||||
:disabled="!isEditMode"
|
|
||||||
:hasFocus="editorFocus"
|
|
||||||
@change="yamlCodeChange"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div v-if="isEditMode">
|
<div v-if="isEditMode">
|
||||||
<!-- Volumes -->
|
<!-- Volumes -->
|
||||||
@ -231,7 +222,7 @@
|
|||||||
<prism-editor v-if="false" v-model="yamlConfig" class="yaml-editor" :highlight="highlighter" line-numbers @input="yamlCodeChange"></prism-editor>
|
<prism-editor v-if="false" v-model="yamlConfig" class="yaml-editor" :highlight="highlighter" line-numbers @input="yamlCodeChange"></prism-editor>
|
||||||
</div>-->
|
</div>-->
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</fieldset>
|
||||||
|
|
||||||
<div v-if="!stack.isManagedByDockge && !processing">
|
<div v-if="!stack.isManagedByDockge && !processing">
|
||||||
{{ $t("stackNotManagedByDockgeMsg") }}
|
{{ $t("stackNotManagedByDockgeMsg") }}
|
||||||
@ -246,11 +237,8 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
import CodeMirror from "vue-codemirror6";
|
import ImageVulnerabilities from "../components/ImageVulnerabilities.vue";
|
||||||
import { yaml } from "@codemirror/lang-yaml";
|
import StackConfigEditor from "../components/StackConfigEditor.vue";
|
||||||
import { python } from "@codemirror/lang-python";
|
|
||||||
import { dracula as editorTheme } from "thememirror";
|
|
||||||
import { lineNumbers, EditorView } from "@codemirror/view";
|
|
||||||
import { parseDocument, Document } from "yaml";
|
import { parseDocument, Document } from "yaml";
|
||||||
|
|
||||||
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
|
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
|
||||||
@ -266,7 +254,8 @@ import {
|
|||||||
import { BModal } from "bootstrap-vue-next";
|
import { BModal } from "bootstrap-vue-next";
|
||||||
import NetworkInput from "../components/NetworkInput.vue";
|
import NetworkInput from "../components/NetworkInput.vue";
|
||||||
import dotenv from "dotenv";
|
import dotenv from "dotenv";
|
||||||
import { ref } from "vue";
|
import { markRaw } from "vue";
|
||||||
|
import { analyzeEnv } from "../../../common/env-file";
|
||||||
|
|
||||||
const template = `
|
const template = `
|
||||||
services:
|
services:
|
||||||
@ -278,16 +267,15 @@ services:
|
|||||||
`;
|
`;
|
||||||
const envDefault = "# VARIABLE=value #comment";
|
const envDefault = "# VARIABLE=value #comment";
|
||||||
|
|
||||||
let yamlErrorTimeout = null;
|
|
||||||
|
|
||||||
let serviceStatusTimeout = null;
|
let serviceStatusTimeout = null;
|
||||||
let dockerStatsTimeout = null;
|
let dockerStatsTimeout = null;
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
components: {
|
components: {
|
||||||
|
ImageVulnerabilities,
|
||||||
|
StackConfigEditor,
|
||||||
NetworkInput,
|
NetworkInput,
|
||||||
FontAwesomeIcon,
|
FontAwesomeIcon,
|
||||||
CodeMirror,
|
|
||||||
BModal,
|
BModal,
|
||||||
},
|
},
|
||||||
beforeRouteUpdate(to, from, next) {
|
beforeRouteUpdate(to, from, next) {
|
||||||
@ -296,39 +284,19 @@ export default {
|
|||||||
beforeRouteLeave(to, from, next) {
|
beforeRouteLeave(to, from, next) {
|
||||||
this.exitConfirm(next);
|
this.exitConfirm(next);
|
||||||
},
|
},
|
||||||
setup() {
|
|
||||||
const editorFocus = ref(false);
|
|
||||||
|
|
||||||
const focusEffectHandler = (state, focusing) => {
|
|
||||||
editorFocus.value = focusing;
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const extensions = [
|
|
||||||
editorTheme,
|
|
||||||
yaml(),
|
|
||||||
lineNumbers(),
|
|
||||||
EditorView.focusChangeEffect.of(focusEffectHandler)
|
|
||||||
];
|
|
||||||
|
|
||||||
const extensionsEnv = [
|
|
||||||
editorTheme,
|
|
||||||
python(),
|
|
||||||
lineNumbers(),
|
|
||||||
EditorView.focusChangeEffect.of(focusEffectHandler)
|
|
||||||
];
|
|
||||||
|
|
||||||
return { extensions,
|
|
||||||
extensionsEnv,
|
|
||||||
editorFocus };
|
|
||||||
},
|
|
||||||
yamlDoc: null, // For keeping the yaml comments
|
|
||||||
data() {
|
data() {
|
||||||
return {
|
return {
|
||||||
jsonConfig: {},
|
jsonConfig: {},
|
||||||
envsubstJSONConfig: {},
|
envsubstJSONConfig: {},
|
||||||
yamlError: "",
|
yamlError: "",
|
||||||
|
yamlDoc: null,
|
||||||
|
updatingFromYaml: false,
|
||||||
|
savedConfig: null,
|
||||||
|
saveError: "",
|
||||||
processing: true,
|
processing: true,
|
||||||
|
autoUpdate: null,
|
||||||
|
autoUpdateSaving: false,
|
||||||
|
imageScanSupported: false,
|
||||||
showProgressTerminal: false,
|
showProgressTerminal: false,
|
||||||
progressTerminalRows: PROGRESS_TERMINAL_ROWS,
|
progressTerminalRows: PROGRESS_TERMINAL_ROWS,
|
||||||
combinedTerminalRows: COMBINED_TERMINAL_ROWS,
|
combinedTerminalRows: COMBINED_TERMINAL_ROWS,
|
||||||
@ -347,6 +315,14 @@ export default {
|
|||||||
};
|
};
|
||||||
},
|
},
|
||||||
computed: {
|
computed: {
|
||||||
|
dirty() {
|
||||||
|
return this.isEditMode && this.savedConfig !== null
|
||||||
|
&& (this.stack.composeYAML !== this.savedConfig.yaml || this.stack.composeENV !== this.savedConfig.env
|
||||||
|
|| this.stack.name !== this.savedConfig.name || this.endpoint !== this.savedConfig.endpoint);
|
||||||
|
},
|
||||||
|
hasConfigErrors() {
|
||||||
|
return Boolean(this.yamlError) || analyzeEnv(this.stack.composeENV || "").some(issue => issue.severity === "error");
|
||||||
|
},
|
||||||
endpointDisplay() {
|
endpointDisplay() {
|
||||||
return this.$root.endpointDisplayFunction(this.endpoint);
|
return this.$root.endpointDisplayFunction(this.endpoint);
|
||||||
},
|
},
|
||||||
@ -431,28 +407,21 @@ export default {
|
|||||||
watch: {
|
watch: {
|
||||||
"stack.composeYAML": {
|
"stack.composeYAML": {
|
||||||
handler() {
|
handler() {
|
||||||
if (this.editorFocus) {
|
this.yamlCodeChange();
|
||||||
console.debug("yaml code changed");
|
|
||||||
this.yamlCodeChange();
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
deep: true,
|
deep: true,
|
||||||
},
|
},
|
||||||
|
|
||||||
"stack.composeENV": {
|
"stack.composeENV": {
|
||||||
handler() {
|
handler() {
|
||||||
if (this.editorFocus) {
|
this.updateEnvironmentPreview();
|
||||||
console.debug("env code changed");
|
|
||||||
this.yamlCodeChange();
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
deep: true,
|
deep: true,
|
||||||
},
|
},
|
||||||
|
|
||||||
jsonConfig: {
|
jsonConfig: {
|
||||||
handler() {
|
handler() {
|
||||||
if (!this.editorFocus) {
|
if (!this.updatingFromYaml && !this.yamlError) {
|
||||||
console.debug("jsonConfig changed");
|
|
||||||
|
|
||||||
let doc = new Document(this.jsonConfig);
|
let doc = new Document(this.jsonConfig);
|
||||||
|
|
||||||
@ -462,10 +431,11 @@ export default {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.stack.composeYAML = doc.toString();
|
this.stack.composeYAML = doc.toString();
|
||||||
this.yamlDoc = doc;
|
this.yamlDoc = markRaw(doc);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
deep: true,
|
deep: true,
|
||||||
|
flush: "sync",
|
||||||
},
|
},
|
||||||
|
|
||||||
$route(to, from) {
|
$route(to, from) {
|
||||||
@ -473,6 +443,7 @@ export default {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
mounted() {
|
mounted() {
|
||||||
|
window.addEventListener("beforeunload", this.confirmPageExit);
|
||||||
if (this.isAdd) {
|
if (this.isAdd) {
|
||||||
this.processing = false;
|
this.processing = false;
|
||||||
this.isEditMode = true;
|
this.isEditMode = true;
|
||||||
@ -503,6 +474,7 @@ export default {
|
|||||||
};
|
};
|
||||||
|
|
||||||
this.yamlCodeChange();
|
this.yamlCodeChange();
|
||||||
|
this.captureSavedConfig();
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
this.stack.name = this.$route.params.stackName;
|
this.stack.name = this.$route.params.stackName;
|
||||||
@ -513,7 +485,8 @@ export default {
|
|||||||
this.requestDockerStats();
|
this.requestDockerStats();
|
||||||
},
|
},
|
||||||
unmounted() {
|
unmounted() {
|
||||||
|
window.removeEventListener("beforeunload", this.confirmPageExit);
|
||||||
|
this.exitAction();
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
startServiceStatusTimeout() {
|
startServiceStatusTimeout() {
|
||||||
@ -558,7 +531,7 @@ export default {
|
|||||||
},
|
},
|
||||||
|
|
||||||
exitConfirm(next) {
|
exitConfirm(next) {
|
||||||
if (this.isEditMode) {
|
if (this.dirty) {
|
||||||
if (confirm(this.$t("confirmLeaveStack"))) {
|
if (confirm(this.$t("confirmLeaveStack"))) {
|
||||||
this.exitAction();
|
this.exitAction();
|
||||||
next();
|
next();
|
||||||
@ -572,6 +545,9 @@ export default {
|
|||||||
},
|
},
|
||||||
|
|
||||||
exitAction() {
|
exitAction() {
|
||||||
|
if (this.stopServiceStatusTimeout && this.stopDockerStatsTimeout) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
console.log("exitAction");
|
console.log("exitAction");
|
||||||
this.stopServiceStatusTimeout = true;
|
this.stopServiceStatusTimeout = true;
|
||||||
this.stopDockerStatsTimeout = true;
|
this.stopDockerStatsTimeout = true;
|
||||||
@ -592,19 +568,52 @@ export default {
|
|||||||
this.$root.emitAgent(this.endpoint, "getStack", this.stack.name, (res) => {
|
this.$root.emitAgent(this.endpoint, "getStack", this.stack.name, (res) => {
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
this.stack = res.stack;
|
this.stack = res.stack;
|
||||||
|
this.autoUpdate = res.autoUpdate ?? null;
|
||||||
|
this.imageScanSupported = res.imageScanSupported === true;
|
||||||
this.yamlCodeChange();
|
this.yamlCodeChange();
|
||||||
|
this.captureSavedConfig();
|
||||||
|
this.saveError = "";
|
||||||
this.processing = false;
|
this.processing = false;
|
||||||
this.bindTerminal();
|
this.bindTerminal();
|
||||||
} else {
|
} else {
|
||||||
this.$root.toastRes(res);
|
this.$root.toastRes(res);
|
||||||
|
this.processing = false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save the update policy on the host that runs this stack.
|
||||||
|
* @param {Event} event Change event from the update switch
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async setAutoUpdate(event) {
|
||||||
|
const input = event.target;
|
||||||
|
this.autoUpdateSaving = true;
|
||||||
|
try {
|
||||||
|
const res = await this.$root.getSocket().timeout(15000).emitWithAck(
|
||||||
|
"agent", this.endpoint, "setStackAutoUpdate", this.stack.name, input.checked
|
||||||
|
);
|
||||||
|
if (res.ok) {
|
||||||
|
this.autoUpdate = res.autoUpdate;
|
||||||
|
} else {
|
||||||
|
this.$root.toastRes(res);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
this.$root.toastError("autoUpdateSaveFailed");
|
||||||
|
} finally {
|
||||||
|
input.checked = this.autoUpdate.enabled;
|
||||||
|
this.autoUpdateSaving = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
deployStack() {
|
deployStack() {
|
||||||
|
if (this.hasConfigErrors) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.processing = true;
|
this.processing = true;
|
||||||
|
|
||||||
if (!this.jsonConfig.services) {
|
if (!this.jsonConfig.services || Object.keys(this.jsonConfig.services).length === 0) {
|
||||||
this.$root.toastError("No services found in compose.yaml");
|
this.$root.toastError("No services found in compose.yaml");
|
||||||
this.processing = false;
|
this.processing = false;
|
||||||
return;
|
return;
|
||||||
@ -633,29 +642,61 @@ export default {
|
|||||||
|
|
||||||
this.bindTerminal();
|
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.processing = false;
|
||||||
this.$root.toastRes(res);
|
this.$root.toastRes(res);
|
||||||
|
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
this.isEditMode = false;
|
this.isEditMode = false;
|
||||||
|
this.captureSavedConfig();
|
||||||
this.$router.push(this.url);
|
this.$router.push(this.url);
|
||||||
|
} else {
|
||||||
|
this.saveError = res.msg || "editorSaveFailed";
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
saveStack() {
|
async saveStack() {
|
||||||
|
if (!this.isEditMode || this.processing || this.hasConfigErrors || (!this.isAdd && !this.dirty)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.processing = true;
|
this.processing = true;
|
||||||
|
this.saveError = "";
|
||||||
this.$root.emitAgent(this.stack.endpoint, "saveStack", this.stack.name, this.stack.composeYAML, this.stack.composeENV, this.isAdd, (res) => {
|
const isAdd = this.isAdd;
|
||||||
this.processing = false;
|
const submitted = {
|
||||||
this.$root.toastRes(res);
|
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) {
|
if (res.ok) {
|
||||||
this.isEditMode = false;
|
this.stack.revision = res.revision ?? this.stack.revision;
|
||||||
this.$router.push(this.url);
|
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() {
|
startStack() {
|
||||||
@ -713,6 +754,9 @@ export default {
|
|||||||
},
|
},
|
||||||
|
|
||||||
discardStack() {
|
discardStack() {
|
||||||
|
if (this.dirty && !confirm(this.$t("confirmLeaveStack"))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.loadStack();
|
this.loadStack();
|
||||||
this.isEditMode = false;
|
this.isEditMode = false;
|
||||||
},
|
},
|
||||||
@ -724,6 +768,9 @@ export default {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const config = doc.toJS() ?? {};
|
const config = doc.toJS() ?? {};
|
||||||
|
if (typeof config !== "object" || Array.isArray(config)) {
|
||||||
|
throw new Error(this.$t("editorYamlMapping"));
|
||||||
|
}
|
||||||
|
|
||||||
// Check data types
|
// Check data types
|
||||||
// "services" must be an object
|
// "services" must be an object
|
||||||
@ -745,26 +792,47 @@ export default {
|
|||||||
try {
|
try {
|
||||||
let { config, doc } = this.yamlToJSON(this.stack.composeYAML);
|
let { config, doc } = this.yamlToJSON(this.stack.composeYAML);
|
||||||
|
|
||||||
this.yamlDoc = doc;
|
this.updatingFromYaml = true;
|
||||||
this.jsonConfig = config;
|
this.yamlDoc = markRaw(doc);
|
||||||
|
|
||||||
let env = dotenv.parse(this.stack.composeENV);
|
|
||||||
let envYAML = envsubstYAML(this.stack.composeYAML, env);
|
|
||||||
this.envsubstJSONConfig = this.yamlToJSON(envYAML).config;
|
|
||||||
|
|
||||||
clearTimeout(yamlErrorTimeout);
|
|
||||||
this.yamlError = "";
|
this.yamlError = "";
|
||||||
|
this.jsonConfig = config;
|
||||||
|
this.updateEnvironmentPreview();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
clearTimeout(yamlErrorTimeout);
|
this.yamlError = e.message;
|
||||||
|
} finally {
|
||||||
|
this.updatingFromYaml = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
if (this.yamlError) {
|
/** Refresh interpolation without rewriting either source file. */
|
||||||
this.yamlError = e.message;
|
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 {
|
/** Remember the content confirmed by the server for dirty tracking. */
|
||||||
yamlErrorTimeout = setTimeout(() => {
|
captureSavedConfig() {
|
||||||
this.yamlError = e.message;
|
this.savedConfig = {
|
||||||
}, 3000);
|
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 = "";
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@ -773,11 +841,13 @@ export default {
|
|||||||
},
|
},
|
||||||
|
|
||||||
checkYAML() {
|
checkYAML() {
|
||||||
|
return !this.hasConfigErrors;
|
||||||
},
|
},
|
||||||
|
|
||||||
addContainer() {
|
addContainer() {
|
||||||
this.checkYAML();
|
if (!this.checkYAML()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (this.jsonConfig.services[this.newContainerName]) {
|
if (this.jsonConfig.services[this.newContainerName]) {
|
||||||
this.$root.toastError("Container name already exists");
|
this.$root.toastError("Container name already exists");
|
||||||
|
|||||||
@ -1,11 +1,32 @@
|
|||||||
<template>
|
<template>
|
||||||
<div class="container-fluid">
|
<div class="container-fluid">
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div v-if="!$root.isMobile" class="col-12 col-md-4 col-xl-3">
|
<div v-if="desktop" class="col-md-4 col-xl-3">
|
||||||
<div>
|
<StackList class="stack-navigation stack-nav-sidebar" />
|
||||||
<router-link to="/compose" class="btn btn-primary mb-3"><font-awesome-icon icon="plus" /> {{ $t("compose") }}</router-link>
|
</div>
|
||||||
</div>
|
<div v-else class="col-12 mb-3 stack-navigation">
|
||||||
<StackList :scrollbar="true" />
|
<DialogRoot v-model:open="stackListOpen" lazy-mount>
|
||||||
|
<DialogTrigger type="button" class="stack-nav-button">
|
||||||
|
<font-awesome-icon icon="list" aria-hidden="true" /> {{ $t("stackListTitle") }}
|
||||||
|
</DialogTrigger>
|
||||||
|
<Teleport to="body">
|
||||||
|
<DialogBackdrop class="stack-nav-backdrop" />
|
||||||
|
<DialogPositioner class="stack-nav-positioner">
|
||||||
|
<DialogContent class="stack-navigation stack-nav-drawer">
|
||||||
|
<StackList @navigate="stackListOpen = false">
|
||||||
|
<template #title>
|
||||||
|
<DialogTitle class="stack-nav-title">{{ $t("stackListTitle") }}</DialogTitle>
|
||||||
|
</template>
|
||||||
|
<template #close>
|
||||||
|
<DialogCloseTrigger type="button" class="stack-nav-button stack-nav-close" :aria-label="$t('stackListClose')">
|
||||||
|
<font-awesome-icon icon="times" aria-hidden="true" />
|
||||||
|
</DialogCloseTrigger>
|
||||||
|
</template>
|
||||||
|
</StackList>
|
||||||
|
</DialogContent>
|
||||||
|
</DialogPositioner>
|
||||||
|
</Teleport>
|
||||||
|
</DialogRoot>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div ref="container" class="col-12 col-md-8 col-xl-9 mb-3">
|
<div ref="container" class="col-12 col-md-8 col-xl-9 mb-3">
|
||||||
@ -17,20 +38,52 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
import { DialogBackdrop, DialogCloseTrigger, DialogContent, DialogPositioner, DialogRoot, DialogTitle, DialogTrigger } from "@ark-ui/vue/dialog";
|
||||||
import StackList from "../components/StackList.vue";
|
import StackList from "../components/StackList.vue";
|
||||||
|
import "../styles/stack-navigation.css";
|
||||||
|
|
||||||
|
const desktopViewport = window.matchMedia("(min-width: 768px)");
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
components: {
|
components: {
|
||||||
|
DialogBackdrop,
|
||||||
|
DialogCloseTrigger,
|
||||||
|
DialogContent,
|
||||||
|
DialogPositioner,
|
||||||
|
DialogRoot,
|
||||||
|
DialogTitle,
|
||||||
|
DialogTrigger,
|
||||||
StackList,
|
StackList,
|
||||||
},
|
},
|
||||||
data() {
|
data() {
|
||||||
return {
|
return {
|
||||||
height: 0
|
height: 0,
|
||||||
|
desktop: desktopViewport.matches,
|
||||||
|
stackListOpen: false,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
watch: {
|
||||||
|
"$route.fullPath"() {
|
||||||
|
this.stackListOpen = false;
|
||||||
|
},
|
||||||
|
},
|
||||||
mounted() {
|
mounted() {
|
||||||
this.height = this.$refs.container.offsetHeight;
|
this.height = this.$refs.container.offsetHeight;
|
||||||
|
desktopViewport.addEventListener("change", this.updateViewport);
|
||||||
|
},
|
||||||
|
beforeUnmount() {
|
||||||
|
desktopViewport.removeEventListener("change", this.updateViewport);
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
/**
|
||||||
|
* Switch navigation layouts at Bootstrap's medium breakpoint.
|
||||||
|
* @param {MediaQueryListEvent} event The viewport match state
|
||||||
|
* @returns {void}
|
||||||
|
*/
|
||||||
|
updateViewport(event) {
|
||||||
|
this.stackListOpen = false;
|
||||||
|
this.desktop = event.matches;
|
||||||
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@ -137,15 +137,21 @@ export default {
|
|||||||
* Save Settings
|
* Save Settings
|
||||||
* @param {saveSettingsCB} [callback]
|
* @param {saveSettingsCB} [callback]
|
||||||
* @param {string} [currentPassword] Only need for disableAuth to true
|
* @param {string} [currentPassword] Only need for disableAuth to true
|
||||||
|
* @param {boolean} [disableAuth] New value when explicitly changing authentication
|
||||||
*/
|
*/
|
||||||
saveSettings(callback, currentPassword) {
|
saveSettings(callback, currentPassword, disableAuth) {
|
||||||
let valid = this.validateSettings();
|
let valid = this.validateSettings();
|
||||||
if (valid.success) {
|
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.$root.toastRes(res);
|
||||||
this.loadSettings();
|
this.loadSettings();
|
||||||
|
|
||||||
if (callback) {
|
if (res.ok && callback) {
|
||||||
callback();
|
callback();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@ -382,18 +382,6 @@ optgroup {
|
|||||||
color: $dark-font-color;
|
color: $dark-font-color;
|
||||||
}
|
}
|
||||||
|
|
||||||
.stack-list {
|
|
||||||
.item {
|
|
||||||
&:hover {
|
|
||||||
background-color: $dark-bg2;
|
|
||||||
}
|
|
||||||
|
|
||||||
&.active {
|
|
||||||
background-color: $dark-bg2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 550px) {
|
@media (max-width: 550px) {
|
||||||
.table-shadow-box {
|
.table-shadow-box {
|
||||||
tbody {
|
tbody {
|
||||||
@ -478,46 +466,6 @@ optgroup {
|
|||||||
opacity: 0;
|
opacity: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.stack-list {
|
|
||||||
&.scrollbar {
|
|
||||||
overflow-y: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 770px) {
|
|
||||||
&.scrollbar {
|
|
||||||
height: calc(100% - 97px);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.item {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
height: 52px;
|
|
||||||
text-decoration: none;
|
|
||||||
border-radius: 10px;
|
|
||||||
transition: all ease-in-out 0.15s;
|
|
||||||
width: 100%;
|
|
||||||
padding: 0 8px;
|
|
||||||
|
|
||||||
&.disabled {
|
|
||||||
opacity: 0.3;
|
|
||||||
}
|
|
||||||
|
|
||||||
&:hover {
|
|
||||||
background-color: $highlight-white;
|
|
||||||
}
|
|
||||||
|
|
||||||
&.active {
|
|
||||||
background-color: #cdf8f4;
|
|
||||||
}
|
|
||||||
|
|
||||||
.title {
|
|
||||||
display: inline-block;
|
|
||||||
margin-top: -4px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.alert-success {
|
.alert-success {
|
||||||
color: #122f21;
|
color: #122f21;
|
||||||
background-color: $primary;
|
background-color: $primary;
|
||||||
|
|||||||
318
frontend/src/styles/stack-navigation.css
Normal file
318
frontend/src/styles/stack-navigation.css
Normal 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;
|
||||||
|
}
|
||||||
@ -3,6 +3,7 @@ import vue from "@vitejs/plugin-vue";
|
|||||||
import Components from "unplugin-vue-components/vite";
|
import Components from "unplugin-vue-components/vite";
|
||||||
import { BootstrapVueNextResolver } from "unplugin-vue-components/resolvers";
|
import { BootstrapVueNextResolver } from "unplugin-vue-components/resolvers";
|
||||||
import viteCompression from "vite-plugin-compression";
|
import viteCompression from "vite-plugin-compression";
|
||||||
|
import panda from "@pandacss/dev/postcss";
|
||||||
import "vue";
|
import "vue";
|
||||||
|
|
||||||
const viteCompressionFilter = /\.(js|mjs|json|css|html|svg)$/i;
|
const viteCompressionFilter = /\.(js|mjs|json|css|html|svg)$/i;
|
||||||
@ -16,6 +17,11 @@ export default defineConfig({
|
|||||||
"FRONTEND_VERSION": JSON.stringify(process.env.npm_package_version),
|
"FRONTEND_VERSION": JSON.stringify(process.env.npm_package_version),
|
||||||
},
|
},
|
||||||
root: "./frontend",
|
root: "./frontend",
|
||||||
|
css: {
|
||||||
|
postcss: {
|
||||||
|
plugins: [ panda({ codegen: false }) ],
|
||||||
|
},
|
||||||
|
},
|
||||||
build: {
|
build: {
|
||||||
outDir: "../frontend-dist",
|
outDir: "../frontend-dist",
|
||||||
},
|
},
|
||||||
|
|||||||
2389
package-lock.json
generated
2389
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -59,13 +59,20 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@actions/github": "^6.0.0",
|
"@actions/github": "^6.0.0",
|
||||||
|
"@ark-ui/vue": "~5.40.0",
|
||||||
|
"@codemirror/commands": "6.10.1",
|
||||||
"@codemirror/lang-python": "^6.1.7",
|
"@codemirror/lang-python": "^6.1.7",
|
||||||
"@codemirror/lang-yaml": "^6.1.2",
|
"@codemirror/lang-yaml": "^6.1.2",
|
||||||
|
"@codemirror/language": "6.12.1",
|
||||||
|
"@codemirror/lint": "6.9.2",
|
||||||
|
"@codemirror/search": "6.5.11",
|
||||||
|
"@codemirror/view": "6.39.6",
|
||||||
"@fontsource/jetbrains-mono": "^5.2.5",
|
"@fontsource/jetbrains-mono": "^5.2.5",
|
||||||
"@fortawesome/fontawesome-svg-core": "6.4.2",
|
"@fortawesome/fontawesome-svg-core": "6.4.2",
|
||||||
"@fortawesome/free-regular-svg-icons": "6.4.2",
|
"@fortawesome/free-regular-svg-icons": "6.4.2",
|
||||||
"@fortawesome/free-solid-svg-icons": "6.4.2",
|
"@fortawesome/free-solid-svg-icons": "6.4.2",
|
||||||
"@fortawesome/vue-fontawesome": "3.0.3",
|
"@fortawesome/vue-fontawesome": "3.0.3",
|
||||||
|
"@pandacss/dev": "~2.5.0",
|
||||||
"@types/bcryptjs": "^2.4.6",
|
"@types/bcryptjs": "^2.4.6",
|
||||||
"@types/bootstrap": "~5.2.10",
|
"@types/bootstrap": "~5.2.10",
|
||||||
"@types/command-exists": "~1.2.3",
|
"@types/command-exists": "~1.2.3",
|
||||||
|
|||||||
38
panda.config.ts
Normal file
38
panda.config.ts
Normal 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",
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue
Block a user