Update Dockge fork and publish Docker images to Gitea
All checks were successful
Docker image / publish (push) Successful in 1m30s

This commit is contained in:
Weapie 2026-11-11 17:01:23 +01:00
parent 720eade8b5
commit b401bd7472
185 changed files with 7717 additions and 7250 deletions

View File

@ -9,7 +9,7 @@ tmp
# Docker extra
docker
frontend
frontend-dist
.editorconfig
.eslintrc.cjs
.git

View File

@ -0,0 +1,46 @@
name: Docker image
on:
push:
branches: [master]
workflow_dispatch:
jobs:
publish:
runs-on: ubuntu-latest
timeout-minutes: 35
container:
image: docker:28-cli
env:
REGISTRY: git.jfritzsche.de
IMAGE: git.jfritzsche.de/jf/dockge
steps:
- name: Install checkout dependencies
run: apk add --no-cache git nodejs
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
- name: Build Linux image
run: |
set -eu
docker buildx build --platform linux/amd64 --target release --load \
--provenance=false --sbom=false \
--label "org.opencontainers.image.source=$GITHUB_SERVER_URL/$GITHUB_REPOSITORY" \
--label "org.opencontainers.image.revision=$GITHUB_SHA" \
--tag "$IMAGE:sha-$GITHUB_SHA" --tag "$IMAGE:latest" \
--file docker/Dockerfile .
- name: Publish commit and latest tags
env:
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
run: |
set -eu
export DOCKER_CONFIG
DOCKER_CONFIG=$(mktemp -d)
trap 'rm -rf "$DOCKER_CONFIG"' EXIT
printf '%s' "$REGISTRY_TOKEN" | docker login "$REGISTRY" --username jf --password-stdin
docker push "$IMAGE:sha-$GITHUB_SHA"
docker push "$IMAGE:latest"

289
README.md
View File

@ -1,207 +1,178 @@
<div align="center" width="100%">
<img src="./frontend/public/icon.svg" width="128" alt="" />
</div>
# Dockge · Weapie-Fork
# Dockge
Dockge verwaltet Docker-Compose-Stacks über eine Weboberfläche. Dieser Fork des ursprünglichen Dockge von Louis Lam wird von **Weapie** weitergepflegt. Er verwendet shadcn-vue mit Nova, Mist und Phosphor-Icons. [Ursprüngliches Dockge](https://github.com/louislam/dockge) · [UI-Konfiguration](components.json)
A fancy, easy-to-use and reactive self-hosted docker compose.yaml stack-oriented manager.
![Stack-Übersicht mit zwei laufenden Diensten im Demo-Stack](docs/images/stack-uebersicht.png)
[![GitHub Repo stars](https://img.shields.io/github/stars/louislam/dockge?logo=github&style=flat)](https://github.com/louislam/dockge) [![Docker Pulls](https://img.shields.io/docker/pulls/louislam/dockge?logo=docker)](https://hub.docker.com/r/louislam/dockge/tags) [![Docker Image Version (latest semver)](https://img.shields.io/docker/v/louislam/dockge/latest?label=docker%20image%20ver.)](https://hub.docker.com/r/louislam/dockge/tags) [![GitHub last commit (branch)](https://img.shields.io/github/last-commit/louislam/dockge/master?logo=github)](https://github.com/louislam/dockge/commits/master/)
[Installation](#installation) · [Stacks](#stacks-verwalten) · [Updates und Scans](#updates-und-schwachstellenscans) · [Images und Volumes](#images-und-volumes) · [Datei-Explorer](#datei-explorer) · [Betrieb](#betrieb-und-fehlerbehebung)
<img src="https://github.com/louislam/dockge/assets/1336778/26a583e1-ecb1-4a8d-aedf-76157d714ad7" width="900" alt="" />
## Installation
View Video: https://youtu.be/AWAlOQeNpgU?t=48
Für die Installation brauchst du den Quellcode dieses Forks und einen erreichbaren Docker-Daemon für **Linux-Container**. Unter Linux installierst du Docker Engine mit dem Compose-Plugin. Unter Windows gehört Compose zu Docker Desktop. Der Build benötigt Internetzugriff für die Basis-Images, npm-Pakete und Grype. Das Image enthält Grype für **amd64** und **arm64**. [Docker Engine](https://docs.docker.com/engine/install/) · [Docker Compose](https://docs.docker.com/compose/install/) · [Docker Desktop für Windows](https://docs.docker.com/desktop/setup/install/windows-install/)
## ⭐ Features
Führe die Befehle im Projektordner mit der [compose.yaml](compose.yaml) aus. Compose baut aus diesem Quellcode das lokale Image `dockge:local`.
- 🧑‍💼 Manage your `compose.yaml` files
- Create/Edit/Start/Stop/Restart/Delete
- Update Docker Images
- ⌨️ Interactive Editor for `compose.yaml`
- 🦦 Interactive Web Terminal
- 🕷️ (1.4.0 🆕) Multiple agents support - You can manage multiple stacks from different Docker hosts in one single interface
- 🏪 Convert `docker run ...` commands into `compose.yaml`
- 📙 File based structure - Dockge won't kidnap your compose files, they are stored on your drive as usual. You can interact with them using normal `docker compose` commands
### Fertiges Image aus Gitea
<img src="https://github.com/louislam/dockge/assets/1336778/cc071864-592e-4909-b73a-343a57494002" width=300 />
Für Linux auf **amd64** stellt Gitea das Image `git.jfritzsche.de/jf/dockge:latest` bereit. Führe zuerst die Vorbereitung des Stack-Verzeichnisses für dein Betriebssystem aus. Lege dann neben der `compose.yaml` eine Datei `compose.registry.yaml` mit folgendem Inhalt an.
- 🚄 Reactive - Everything is just responsive. Progress (Pull/Up/Down) and terminal output are in real-time
- 🐣 Easy-to-use & fancy UI - If you love Uptime Kuma's UI/UX, you will love this one too
![](https://github.com/louislam/dockge/assets/1336778/89fc1023-b069-42c0-a01c-918c495f1a6a)
## 🔧 How to Install
Requirements:
- [Docker](https://docs.docker.com/engine/install/) 20+ / Podman
- (Podman only) podman-docker (Debian: `apt install podman-docker`)
- OS:
- Major Linux distros that can run Docker/Podman such as:
- ✅ Ubuntu
- ✅ Debian (Bullseye or newer)
- ✅ Raspbian (Bullseye or newer)
- ✅ CentOS
- ✅ Fedora
- ✅ ArchLinux
- ❌ Debian/Raspbian Buster or lower is not supported
- ❌ Windows (Will be supported later)
- Arch: armv7, arm64, amd64 (a.k.a x86_64)
### Basic
- Default Stacks Directory: `/opt/stacks`
- Default Port: 5001
```
# Create directories that store your stacks and stores Dockge's stack
mkdir -p /opt/stacks /opt/dockge
cd /opt/dockge
# Download the compose.yaml
curl https://raw.githubusercontent.com/louislam/dockge/master/compose.yaml --output compose.yaml
# Start the server
docker compose up -d
# If you are using docker-compose V1 or Podman
# docker-compose up -d
```
Dockge is now running on http://localhost:5001
### Advanced
If you want to store your stacks in another directory, you can generate your compose.yaml file by using the following URL with custom query strings.
```
# Download your compose.yaml
curl "https://dockge.kuma.pet/compose.yaml?port=5001&stacksPath=/opt/stacks" --output compose.yaml
```
- port=`5001`
- stacksPath=`/opt/stacks`
Also, once compose is generated/downloaded, add the `PUID` and `PGID` section below to your compose `environment:` section to set stack ownership, otherwise default is `root`
```
# Both PUID and PGID must be set for it to do anything
- PUID=1000 # Set the stack file/dir ownership to this user
- PGID=1000 # Set the stack file/dir ownership to this group
```
Interactive compose.yaml generator is available on:
https://dockge.kuma.pet
### -OR-
Copy and paste your compose from the following:
If you want to store your stacks in another directory, you can change the `DOCKGE_STACKS_DIR` environment variable and volumes.
compose:
```
~~~yaml
services:
dockge:
image: louislam/dockge:1
restart: unless-stopped
ports:
# Host Port:Container Port
- 5001:5001
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./data:/app/data
# If you want to use private registries, you need to share the auth file with Dockge:
# - /root/.docker/:/root/.docker
image: git.jfritzsche.de/jf/dockge:latest
~~~
# Stacks Directory
# Your stacks directory in the host (The paths inside container must be the same as the host)
# ⚠️ If you did it wrong, your data could end up be written into a wrong path.
# ✔️ CORRECT EXAMPLE: - /my-stacks:/my-stacks (Both paths match)
# ❌ WRONG EXAMPLE: - /docker:/my-stacks (Both paths do not match)
- /opt/stacks:/opt/stacks
environment:
# Tell Dockge where your stacks directory is
- DOCKGE_STACKS_DIR=/opt/stacks
# Both PUID and PGID must be set for it to do anything
- PUID=1000 # Set the stack file/dir ownership to this user
- PGID=1000 # Set the stack file/dir ownership to this group
```
~~~sh
docker compose -f compose.yaml -f compose.registry.yaml pull dockge
docker compose -f compose.yaml -f compose.registry.yaml up -d --no-build
~~~
## How to Update
Mit denselben Befehlen aktualisierst du später die Installation. Der [Gitea-Workflow](.gitea/workflows/docker-image.yml) veröffentlicht bei Änderungen an `master` die Tags `latest` und `sha-<Commit>`. Mit einem Commit-Tag kannst du einen bestimmten Build installieren. [Gitea Container Registry](https://docs.gitea.com/usage/packages/container/)
```bash
cd /opt/dockge
docker compose pull && docker compose up -d
```
### Linux
## Screenshots
Das Stack-Verzeichnis ist standardmäßig `/opt/stacks`. Verwende bei einer bestehenden Installation den bisherigen absoluten Pfad.
![](https://github.com/louislam/dockge/assets/1336778/e7ff0222-af2e-405c-b533-4eab04791b40)
~~~bash
docker version
docker compose version
sudo mkdir -p /opt/stacks
docker compose config --quiet
docker compose up -d --build
docker compose ps
~~~
### Windows mit Docker Desktop
![](https://github.com/louislam/dockge/assets/1336778/7139e88c-77ed-4d45-96e3-00b66d36d871)
Starte Docker Desktop mit dem WSL-2-Backend im Modus für Linux-Container. Öffne PowerShell im Projektordner auf einem lokalen Laufwerk, das Docker Desktop einbinden kann. Das Beispiel legt `stacks` neben die Compose-Datei und verwendet den Linux-Pfad, unter dem Docker Desktop das Windows-Laufwerk im Daemon bereitstellt.
![](https://github.com/louislam/dockge/assets/1336778/f019944c-0e87-405b-a1b8-625b35de1eeb)
~~~powershell
docker version
docker compose version
![](https://github.com/louislam/dockge/assets/1336778/a4478d23-b1c4-4991-8768-1a7cad3472e3)
$projectPath = (Get-Location).Path
$drive = $projectPath.Substring(0, 1).ToLowerInvariant()
$pathOnDrive = $projectPath.Substring(2).Replace('\', '/').TrimEnd('/')
New-Item -ItemType Directory -Path (Join-Path $projectPath 'stacks') -Force | Out-Null
$env:DOCKGE_STACKS_DIR = "/run/desktop/mnt/host/$drive$pathOnDrive/stacks"
docker compose config --quiet
docker compose up -d --build
docker compose ps
~~~
## Motivations
Für weitere PowerShell-Sitzungen kannst du den Wert von `$env:DOCKGE_STACKS_DIR` als Zeile `DOCKGE_STACKS_DIR=<Wert>` in die `.env` des **Dockge-Projektordners** eintragen. Das Projekt unter `C:\Projekte\dockge` ergibt beispielsweise `DOCKGE_STACKS_DIR=/run/desktop/mnt/host/c/Projekte/dockge/stacks`. [Docker Desktop und WSL](https://docs.docker.com/desktop/features/wsl/)
- I have been using Portainer for some time, but for the stack management, I am sometimes not satisfied with it. For example, sometimes when I try to deploy a stack, the loading icon keeps spinning for a few minutes without progress. And sometimes error messages are not clear.
- Try to develop with ES Module + TypeScript
### Erster Start
If you love this project, please consider giving it a ⭐.
1. Öffne [http://127.0.0.1:5001](http://127.0.0.1:5001) und erstelle dein Dockge-Konto.
2. Wähle **New stack**, vergib einen Namen und hinterlege eine `compose.yaml`. Für einen ersten Test eignet sich dieser Stack.
~~~yaml
services:
web:
image: nginx:alpine
restart: unless-stopped
ports:
- "127.0.0.1:8081:80"
~~~
## 🗣️ Community and Contribution
3. Klicke auf **Deployen**. Sobald der Container läuft, erreichst du die Beispielseite unter [http://127.0.0.1:8081](http://127.0.0.1:8081).
### Bug Report
https://github.com/louislam/dockge/issues
Dockge bindet die Oberfläche standardmäßig an `127.0.0.1:5001`. Der eingebundene Docker-Socket gibt Dockge weitreichenden Zugriff auf den Host. Beschränke den Zugang auf vertrauenswürdige Personen. Wenn du die Oberfläche über einen Reverse Proxy bereitstellst, verwende HTTPS und leite WebSocket-Verbindungen weiter. [Docker Engine und Sicherheit](https://docs.docker.com/engine/security/)
### Ask for Help / Discussions
https://github.com/louislam/dockge/discussions
## Stacks verwalten
### Translation
If you want to translate Dockge into your language, please read [Translation Guide](https://github.com/louislam/dockge/blob/master/frontend/src/lang/README.md)
- **Übersicht** zeigt Dienste, Status, Ports und die CPU- und Speicherauslastung laufender Container. Du kannst Stacks starten, stoppen, neu starten und Images manuell aktualisieren.
- **Konfiguration** öffnet `compose.yaml` und die Stack-`.env` im Editor mit Suche, Zeilenumbruch und Vollbildansicht.
- **Protokolle** zeigt laufende Stack-Logs. Über die Aktionen eines Dienstes erreichst du dessen Logs, Terminal und Datei-Explorer.
- **Wartung** bündelt den Update-Zeitplan und die Schwachstellenscans.
### Create a Pull Request
Für vorhandene Compose-Stacks erwartet Dockge je einen Unterordner im Stack-Verzeichnis, etwa `/opt/stacks/web/compose.yaml`. Lege die zugehörige `.env` und Dateien für relative Bind-Mounts in der bestehenden Verzeichnisstruktur ab. Wähle danach **Stacks-Ordner durchsuchen** im Kontomenü. Bei laufenden Projekten sollten Projektname und Arbeitsverzeichnis zur vorhandenen Bereitstellung passen. Prüfe diese vor dem erneuten Bereitstellen, damit Docker Compose das richtige Projekt anspricht.
Be sure to read the [guide](https://github.com/louislam/dockge/blob/master/CONTRIBUTING.md), as we don't accept all types of pull requests and don't want to waste your time.
Über **Einstellungen → Global .env** kannst du die Datei `global.env` im Stack-Verzeichnis pflegen. Docker Compose verwendet sie zur Variablenauflösung, wobei die `.env` des jeweiligen Stacks Vorrang hat. Auf der Startseite lässt sich auch ein `docker run`-Befehl in Compose-YAML umwandeln.
## FAQ
### Mehrere Docker-Hosts
#### "Dockge"?
Starte auf jedem zusätzlichen Host eine Dockge-Instanz mit Zugriff auf dessen Docker-Socket. Wähle auf der Startseite deiner Hauptinstanz **Agent hinzufügen** und trage die für sie erreichbare URL sowie die Zugangsdaten der Zielinstanz ein. Bei mehreren verbundenen Hosts kannst du Stacks, Container, Images und Volumes nach Host auswählen. Update- und Bereinigungszeitpläne laufen auf der Instanz, die den jeweiligen Docker-Host verwaltet.
"Dockge" is a coinage word which is created by myself. I originally hoped it sounds like `Dodge`, but apparently many people called it `Dockage`, it is also acceptable.
## Updates und Schwachstellenscans
The naming idea came from Twitch emotes like `sadge`, `bedge` or `wokege`. They all end in `-ge`.
![Stack-Wartung mit Uhrzeit, Wartezeit und Grype-Scanbericht](docs/images/wartung.png)
#### Can I manage a single container without `compose.yaml`?
- **Automatische Image-Updates** sind pro Stack aktivierbar. Wähle unter **Wartung** die tägliche Uhrzeit und eine Zeitzone wie `Europe/Berlin`. Die optionale Wartezeit zählt ab der ersten Erkennung der konkreten neuen Image-Version. Nach Ablauf kann Dockge sie beim nächsten geplanten Lauf bereitstellen. Dockge lädt das neue Image schon beim Erkennen herunter und wartet mit dem Austausch des laufenden Containers. Dienste mit lokalen Builds oder noch nicht bereitgestellten Konfigurationsänderungen werden übersprungen.
- **Images prüfen** scannt die lokalen Image-IDs der Container dieses Stacks. Der Bericht zeigt die Funde nach Schweregrad, betroffene Pakete, gemeldete korrigierte Versionen und den Stand der Datenbank. Der Erstimport der Grype-Datenbank kann einige Minuten dauern. Scanberichte bleiben bis zum Dockge-Neustart im Arbeitsspeicher.
- **Grype** prüft auf unterstützten Linux-Architekturen unabhängig vom Dockge-Image regelmäßig auf neue Versionen. Vor jedem Scanbericht aktualisiert Dockge die Schwachstellendatenbank und kann bei einem fehlgeschlagenen Abruf eine weiterhin gültige lokale Datenbank verwenden. [Grype-Datenbank](https://oss.anchore.com/docs/guides/vulnerability/database/)
The main objective of Dockge is to try to use the docker `compose.yaml` for everything. If you want to manage a single container, you can just use Portainer or Docker CLI.
## Images und Volumes
#### Can I manage existing stacks?
Unter **Einstellungen → Images** siehst du Tags, Größe, Erstellungsdatum und die Container, die ein Image verwenden. Über **Details** kannst du einen Tag mit dem Registry-Stand vergleichen. Kann Dockge die Registry oder die passende Plattform nicht eindeutig prüfen, zeigt es einen unbekannten Status an.
Yes, you can. However, you need to move your compose file into the stacks directory:
![Image-Verwaltung mit verwendeten und ungenutzten Images sowie Tag-Details](docs/images/images.png)
1. Stop your stack
2. Move your compose file into `/opt/stacks/<stackName>/compose.yaml`
3. In Dockge, click the " Scan Stacks Folder" button in the top-right corner's dropdown menu
4. Now you should see your stack in the list
Unter **Einstellungen → Volumes** siehst du den Treiber, den Nutzungsstatus und die referenzierenden Container. Bei beiden Listen zählen auch **gestoppte** Container als Referenzen.
#### Is Dockge a Portainer replacement?
![Volume-Verwaltung mit verwendetem und ungenutztem Volume](docs/images/volumes.png)
Yes or no. Portainer provides a lot of Docker features. While Dockge is currently only focusing on docker-compose with a better user interface and better user experience.
Ungenutzte Einträge lassen sich einzeln löschen. **Alle ungenutzten löschen** bereinigt den gesamten gewählten Docker-Host. Die sichtbaren Suchfilter beeinflussen diese Aktion nicht. Für Images und Volumes gibt es jeweils einen eigenen täglichen Zeitplan mit Uhrzeit und Zeitzone. Beide Bereinigungen sind standardmäßig deaktiviert.
If you want to manage your container with docker-compose only, the answer may be yes.
> **Volumes enthalten Anwendungsdaten.** Docker kann auch benannte lokale Volumes löschen, wenn kein Container sie referenziert. Ein Verweis allein in einer gespeicherten Compose-Datei schützt das Volume nicht. Sichere wichtige Volumes, bevor du eine Bereinigung aktivierst. [Docker-Bereinigung](https://docs.docker.com/engine/manage-resources/pruning/)
If you still need to manage something like docker networks, single containers, the answer may be no.
## Datei-Explorer
#### Can I install both Dockge and Portainer?
Öffne **Docker-Container → Dateien** bei einem laufenden Container. Der gleiche Einstieg steht im Stack beim jeweiligen Dienst zur Verfügung. Der Explorer bietet Ordnernavigation, Suche, Uploads, Downloads und den Download von Ordnern als TAR-Archiv. Du kannst Ordner und Dateien anlegen, kopieren, umbenennen, verschieben und löschen. Textdateien lassen sich direkt bearbeiten.
Yes, you can.
![Datei-Explorer im Ordner /srv/site eines laufenden Demo-Containers](docs/images/datei-explorer.png)
## Others
Der Explorer benötigt die mitgelieferten Shell-Werkzeuge des Zielcontainers, insbesondere `sh` und für Ordnerarchive `tar`. Pro Datei oder Archiv gilt ein Transferlimit von **32 MiB**, für den Texteditor **512 KiB**. Änderungen in der beschreibbaren Container-Schicht können beim Ersetzen des Containers verloren gehen. Lege dauerhaft benötigte Dateien in einem Volume oder Bind-Mount ab. [Docker-Volumes](https://docs.docker.com/engine/storage/volumes/)
Dockge is built on top of [Compose V2](https://docs.docker.com/compose/migrate/). `compose.yaml` also known as `docker-compose.yml`.
## Betrieb und Fehlerbehebung
| Speicherort | Inhalt |
| --- | --- |
| `./data` → `/app/data` | Dockge-Datenbank mit Konto, Einstellungen und Agent-Konfiguration sowie der Cache für aktualisierte Grype-Versionen |
| `DOCKGE_STACKS_DIR` | Stack-Ordner mit Compose-Dateien, Umgebungsvariablen und Update-Regeln |
| Docker-Volume `grype-db` | Lokale Schwachstellendatenbank. Docker Compose versieht den Volume-Namen mit dem Projektnamen. |
| Stack-eigene Docker-Volumes und Bind-Mounts | Anwendungsdaten der bereitgestellten Dienste |
Sichere für einen Umzug die Dockge-Daten, das Stack-Verzeichnis und die jeweiligen Anwendungsdaten. Halte Dockge für eine konsistente Kopie seiner SQLite-Datenbank an. Setze beim Umzug `DOCKGE_STACKS_DIR` auf den passenden Pfad. Quell- und Zielpfad des Stack-Bind-Mounts müssen identisch sein, damit der Docker-Daemon Stack-Pfade und relative Mounts auflösen kann. [Compose-Konfiguration](compose.yaml)
### Dockge aktualisieren und anhalten
Aktualisiere den lokalen Quellcode des Forks. Baue und starte Dockge anschließend im selben Projektordner neu.
~~~sh
docker compose up -d --build
docker compose ps
~~~
Mit `docker compose stop` hältst du Dockge an. `docker compose down` entfernt seinen Container und sein Compose-Netzwerk. `docker compose down --volumes` entfernt zusätzlich das Grype-Datenbank-Volume. Die über Dockge bereitgestellten Stacks sind eigenständige Compose-Projekte. [Docker Compose down](https://docs.docker.com/reference/cli/docker/compose/down/)
### Weitere Einstellungen
Unter **Allgemein** legst du den primären Hostnamen für Links zu veröffentlichten Container-Ports fest. **Erscheinungsbild** steuert Sprache und Farbschema. Unter **Sicherheit** kannst du dein Passwort ändern. Die separate **Konsole** für Docker-Befehle ist standardmäßig deaktiviert. Die Umgebungsvariable `DOCKGE_ENABLE_CONSOLE=true` im Dockge-Dienst schaltet sie frei.
### Häufige Probleme
| Problem | Prüfung |
| --- | --- |
| Docker oder Compose antwortet nicht | Prüfe `docker version` und `docker compose version`. Unter Windows muss Docker Desktop laufen und Linux-Container verwenden. |
| Port 5001 ist belegt | Prüfe mit `docker ps`, welche Instanz den Port nutzt. Passe bei einer zweiten Instanz den Host-Port in `compose.yaml` an. |
| Stack erscheint nicht | Kontrolliere `DOCKGE_STACKS_DIR` und die Unterordner mit Compose-Dateien. Scanne den Stack-Ordner danach erneut. |
| Grype-Scan meldet einen Datenbankfehler | Prüfe freien Docker-Speicher, Netzwerkzugriff auf `grype.anchore.io` und den Datenbankstatus mit `docker compose exec dockge grype db status`. |
| Dockge startet nicht | Lies die Ausgabe von `docker compose logs --tail=100 dockge`. |
| Passwort vergessen | Führe im laufenden Dockge-Container `docker compose exec dockge npm run reset-password` aus. |
## Entwicklung
Für lokale Änderungen benötigt das Projekt Node.js ab **22.14**. Docker muss für Stack-Funktionen verfügbar sein. `npm run dev` startet Frontend und Backend im Entwicklungsmodus. `npm run build:frontend` erstellt das Frontend für die Auslieferung. [Projekt-Skripte](package.json)
~~~sh
npm ci
npm run check-ts
npm run dev
~~~
## Lizenz
[MIT](LICENSE) · Ursprünglich entwickelt von Louis Lam, als Fork weitergepflegt von **Weapie**.

View File

@ -0,0 +1,28 @@
import { AgentSocketHandler } from "../agent-socket-handler";
import type { DockgeServer } from "../dockge-server";
import { callbackError, callbackResult, checkLogin, DockgeSocket, ValidationError } from "../util-server";
import type { AgentSocket } from "../../common/agent-socket";
export class ContainerManagementSocketHandler extends AgentSocketHandler {
create(socket: DockgeSocket, server: DockgeServer, agentSocket: AgentSocket) {
const on = (event: string, fallback: string, action: (...args: unknown[]) => Promise<object>) => {
agentSocket.on(event, async (...args: unknown[]) => {
const callback = args.pop();
if (typeof callback !== "function") {
return;
}
try {
checkLogin(socket);
callbackResult({ ok: true,
...await action(...args) }, callback);
} catch (error) {
callbackError(error instanceof ValidationError ? error : new Error(fallback), callback);
}
});
};
on("listHostContainers", "containerInventoryFailed", async () => ({ items: await server.containerManagement.list() }));
on("containerFiles", "containerFileFailed", request => server.containerFileExplorer.request(socket.id, request));
socket.on("disconnect", () => server.containerFileExplorer.disconnect(socket.id));
}
}

View File

@ -262,13 +262,26 @@ export class DockerSocketHandler extends AgentSocketHandler {
}
});
// down stack
onStackMutation("setStackAutoUpdate", async (name, enabled, callback) => {
if (typeof name !== "string" || !/^[a-z0-9_-]+$/.test(name) || typeof enabled !== "boolean") {
agentSocket.on("getStackAutoUpdate", async (name: unknown, callback) => {
try {
checkLogin(socket);
if (typeof name !== "string" || !/^[a-z0-9_-]+$/.test(name)) {
throw new ValidationError("autoUpdateUnavailable");
}
const stack = await Stack.getStack(server, name);
callbackResult({ ok: true,
autoUpdate: await server.stackAutoUpdate.getPolicy(stack) }, callback);
} catch (error) {
callbackError(error, callback);
}
});
onStackMutation("setStackAutoUpdate", async (name, schedule, callback) => {
if (typeof name !== "string" || !/^[a-z0-9_-]+$/.test(name)) {
throw new ValidationError("Invalid automatic update settings.");
}
const stack = await Stack.getStack(server, name);
const autoUpdate = await server.stackAutoUpdate.setEnabled(stack, enabled);
const autoUpdate = await server.stackAutoUpdate.setPolicy(stack, schedule);
callbackResult({
ok: true,
autoUpdate,

View File

@ -0,0 +1,45 @@
import { AgentSocketHandler } from "../agent-socket-handler";
import type { DockgeServer } from "../dockge-server";
import { callbackError, callbackResult, checkLogin, DockgeSocket, ValidationError } from "../util-server";
import type { AgentSocket } from "../../common/agent-socket";
export class ResourceSocketHandler extends AgentSocketHandler {
create(socket: DockgeSocket, server: DockgeServer, agentSocket: AgentSocket) {
const resources = server.dockerResources;
const on = (event: string, errorKey: string, operation: (...args: unknown[]) => Promise<object>) => {
agentSocket.on(event, async (...args: unknown[]) => {
const callback = args.pop();
try {
checkLogin(socket);
callbackResult({ ok: true,
...await operation(...args) }, callback);
} catch (error) {
callbackError(error instanceof ValidationError ? error : new Error(errorKey), callback);
}
});
};
on("listDockerImages", "resourceLoadFailed", async () => ({ items: await resources.listImages() }));
on("listDockerVolumes", "resourceLoadFailed", async () => ({ items: await resources.listVolumes() }));
on("getResourceCleanup", "resourceLoadFailed", async kind => ({ schedule: await server.resourceCleanup.status(kind) }));
on("setResourceCleanup", "resourceCleanupSaveFailed", async (kind, schedule) => ({
schedule: await server.resourceCleanup.set(kind, schedule),
}));
on("pruneDockerResources", "resourceCleanupFailed", async kind => {
await server.resourceCleanup.prune(kind);
return { msg: "resourceCleanupCompleted",
msgi18n: true };
});
on("checkDockerImageTag", "resourceCheckFailed", async (id, tag) => ({ status: await resources.checkImage(id, tag) }));
on("removeDockerImage", "resourceDeleteFailed", async (id, tag) => {
await resources.removeImage(id, tag);
return { msg: "resourceDeleted",
msgi18n: true };
});
on("removeDockerVolume", "resourceDeleteFailed", async (name, created) => {
await resources.removeVolume(name, created);
return { msg: "resourceDeleted",
msgi18n: true };
});
}
}

View File

@ -1,57 +0,0 @@
import { log } from "./log";
import compareVersions from "compare-versions";
import packageJSON from "../package.json";
import { Settings } from "./settings";
// How much time in ms to wait between update checks
const UPDATE_CHECKER_INTERVAL_MS = 1000 * 60 * 60 * 48;
const CHECK_URL = "https://dockge.kuma.pet/version";
class CheckVersion {
version = packageJSON.version;
latestVersion? : string;
interval? : NodeJS.Timeout;
async startInterval() {
const check = async () => {
if (await Settings.get("checkUpdate") === false) {
return;
}
log.debug("update-checker", "Retrieving latest versions");
try {
const res = await fetch(CHECK_URL);
const data = await res.json();
// For debug
if (process.env.TEST_CHECK_VERSION === "1") {
data.slow = "1000.0.0";
}
const checkBeta = await Settings.get("checkBeta");
if (checkBeta && data.beta) {
if (compareVersions.compare(data.beta, data.slow, ">")) {
this.latestVersion = data.beta;
return;
}
}
if (data.slow) {
this.latestVersion = data.slow;
}
} catch (_) {
log.info("update-checker", "Failed to check for new versions");
}
};
await check();
this.interval = setInterval(check, UPDATE_CHECKER_INTERVAL_MS);
}
}
const checkVersion = new CheckVersion();
export default checkVersion;

View File

@ -0,0 +1,313 @@
import { execFile } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import { posix } from "node:path";
import { promisify } from "node:util";
import { fileChunkBytes, maxContainerFileBytes } from "../common/container-files";
import { containerId, docker } from "./container-management";
import { ValidationError } from "./util-server";
const exec = promisify(execFile);
const transferLimit = 4;
const ttl = 2 * 60 * 1000;
interface Transfer {
owner: string;
id: string;
path: string;
type: "download" | "upload";
data: Buffer;
offset: number;
expected?: string;
busy: boolean;
timer: NodeJS.Timeout;
}
function checkedPath(value: unknown): string {
if (typeof value !== "string" || !value.startsWith("/") || value.includes("\0")
|| Buffer.byteLength(value) > 4096 || posix.normalize(value) !== value || (value !== "/" && value.endsWith("/"))) {
throw new ValidationError("containerFileInvalidPath");
}
return value;
}
// Positional arguments are always data. Reject symbolic-link parents before working on a path.
const shell = `
directory() {
cd -P -- "$1" && [ "$(pwd -P)" = "$1" ]
}
in_parent() {
p=\${1%/*}
directory "\${p:-/}" || exit 24
}
exists() {
[ -e "$1" ] || [ -L "$1" ]
}
`;
const list = `
directory "$1" || exit 24
count=0
for entry in ./* ./.[!.]* ./..?*; do
exists "$entry" || continue
count=$((count + 1))
[ "$count" -le 3000 ] || exit 25
kind=other
if [ -L "$entry" ]; then kind=link
elif [ -d "$entry" ]; then kind=directory
elif [ -f "$entry" ]; then kind=file
fi
metadata=$(stat -c '%s %Y' -- "$entry") || exit 24
printf '%s\\0%s\\0%s\\0' "\${entry#./}" "$kind" "$metadata"
done
`;
const read = `
in_parent "$1"
name=./\${1##*/}
[ ! -L "$name" ] || exit 24
if [ -d "$name" ]; then
tar -cf - -- "$name"
else
[ -f "$name" ] || exit 24
head -c "$2" -- "$name"
fi
`;
const write = `
in_parent "$1"
name=./\${1##*/}
if [ -n "$2" ]; then
[ -f "$name" ] && [ ! -L "$name" ] || exit 23
sum=$(sha256sum < "$name") || exit 24
[ "\${sum%% *}" = "$2" ] || exit 23
mode=$(stat -c '%a' -- "$name") || exit 24
owner=$(stat -c '%u:%g' -- "$name") || exit 24
else
if exists "$name"; then exit 23; fi
fi
temp=$(mktemp ./.dockge.XXXXXX) || exit 24
trap 'rm -f -- "$temp"' EXIT
cat > "$temp" || exit 24
[ "$(stat -c '%s' -- "$temp")" = "$3" ] || exit 24
if [ -n "$2" ]; then
if [ "$(stat -c '%u:%g' -- "$temp")" != "$owner" ]; then
chown -- "$owner" "$temp" || exit 24
fi
chmod -- "$mode" "$temp" || exit 24
[ -f "$name" ] && [ ! -L "$name" ] || exit 23
sum=$(sha256sum < "$name") || exit 24
[ "\${sum%% *}" = "$2" ] || exit 23
mv -fT -- "$temp" "$name" || exit 24
else
mv -nT -- "$temp" "$name" || exit 24
[ ! -e "$temp" ] || exit 23
fi
`;
const change = `
case "$1" in
mkdir)
in_parent "$2"
mkdir -- "./\${2##*/}" || exit 24
;;
delete)
in_parent "$2"
rm -r -- "./\${2##*/}" || exit 24
;;
move|copy)
in_parent "$2"
in_parent "$3"
if exists "./\${3##*/}"; then exit 23; fi
if [ "$1" = move ]; then
mv -nT -- "$2" "./\${3##*/}" && ! exists "$2" || exit 23
else
staging=$(mktemp -d ./.dockge.XXXXXX) || exit 24
trap 'rm -rf -- "$staging"' EXIT
cp -a -- "$2" "$staging/item" || exit 24
mv -nT -- "$staging/item" "./\${3##*/}" || exit 24
! exists "$staging/item" || exit 23
fi
;;
esac
`;
export class ContainerFileExplorer {
private readonly transfers = new Map<string, Transfer>();
disconnect(owner: string) {
for (const [ token, transfer ] of this.transfers) {
if (transfer.owner === owner) {
this.release(token);
}
}
}
async request(owner: string, request: unknown): Promise<object> {
if (!request || typeof request !== "object") {
throw new ValidationError("containerFileInvalidRequest");
}
const args = request as Record<string, unknown>;
const action = args.action;
if (action === "chunk" || action === "finish" || action === "cancel") {
return this.transferRequest(owner, action, args);
}
const id = containerId(args.id);
const path = checkedPath(args.path);
await this.requireRunning(id);
if (action === "list") {
const { stdout } = await docker([ "container", "inspect", "--format", "{{.Name}}", "--", id ]);
const fields = (await this.run(id, list, [ path ])).toString("utf8").split("\0");
const entries = [];
for (let i = 0; i + 2 < fields.length; i += 3) {
const [ size, modified ] = fields[i + 2].split(" ").map(Number);
entries.push({ name: fields[i],
type: fields[i + 1],
size,
modified });
}
return { entries,
name: stdout.trim().replace(/^\//, "") };
}
if (path === "/") {
throw new ValidationError("containerFileInvalidPath");
}
if (action === "download" || action === "upload") {
return this.openTransfer(owner, id, path, action, args);
}
if (action === "mkdir" || action === "delete" || action === "move" || action === "copy") {
const target = action === "move" || action === "copy" ? checkedPath(args.target) : "";
if (target && (target === "/" || target === path || target.startsWith(path + "/") || path.startsWith(target + "/"))) {
throw new ValidationError("containerFileInvalidPath");
}
await this.run(id, change, [ action, path, target ]);
return {};
}
throw new ValidationError("containerFileInvalidRequest");
}
private async requireRunning(id: string) {
const { stdout } = await docker([ "container", "inspect", "--format", "{{.State.Running}} {{.State.Paused}}", "--", id ]);
if (stdout.trim() !== "true false") {
throw new ValidationError("containerFileNotRunning");
}
}
private async run(id: string, script: string, args: string[], input?: Buffer) {
const pending = exec("docker", [
"container", "exec", ...(input ? [ "-i" ] : []), id, "sh", "-c", shell + script, "dockge-files", ...args,
], {
encoding: "buffer",
timeout: 30000,
maxBuffer: maxContainerFileBytes + 1024,
windowsHide: true,
});
if (input) {
pending.child.stdin?.on("error", () => {});
pending.child.stdin?.end(input);
}
try {
return (await pending).stdout;
} catch (error) {
const code = (error as { code?: string | number }).code;
const messages: Record<string, string> = {
"23": "containerFileConflict",
"25": "containerFileTooManyEntries",
"126": "containerFileToolsUnavailable",
"127": "containerFileToolsUnavailable",
ERR_CHILD_PROCESS_STDIO_MAXBUFFER: "containerFileTooLarge",
};
throw new ValidationError(messages[String(code)] || "containerFileFailed");
}
}
private release(token: string) {
const transfer = this.transfers.get(token);
if (transfer) {
clearTimeout(transfer.timer);
this.transfers.delete(token);
}
}
private async openTransfer(owner: string, id: string, path: string, type: Transfer["type"], args: Record<string, unknown>) {
if (this.transfers.size >= transferLimit || Array.from(this.transfers.values()).some(value => value.owner === owner)) {
throw new ValidationError("containerFileTransferBusy");
}
const size = args.size;
const expected = args.expected;
if (type === "upload" && (typeof size !== "number" || !Number.isSafeInteger(size) || size < 0 || size > maxContainerFileBytes
|| (expected !== undefined && (typeof expected !== "string" || !/^[0-9a-f]{64}$/.test(expected))))) {
throw new ValidationError("containerFileInvalidRequest");
}
const token = randomUUID();
const transfer: Transfer = {
owner,
id,
path,
type,
expected: typeof expected === "string" ? expected : undefined,
data: Buffer.alloc(type === "upload" ? Number(size) : 0),
offset: 0,
busy: true,
timer: setTimeout(() => this.release(token), ttl).unref(),
};
this.transfers.set(token, transfer);
try {
if (type === "download") {
transfer.data = await this.run(id, read, [ path, String(maxContainerFileBytes + 1) ]);
if (transfer.data.length > maxContainerFileBytes) {
throw new ValidationError("containerFileTooLarge");
}
}
transfer.busy = false;
return {
token,
size: transfer.data.length,
revision: type === "download" ? createHash("sha256").update(transfer.data).digest("hex") : undefined,
};
} catch (error) {
this.release(token);
throw error;
}
}
private async transferRequest(owner: string, action: string, args: Record<string, unknown>) {
const token = args.token;
const transfer = typeof token === "string" && this.transfers.get(token);
if (!transfer || transfer.owner !== owner || transfer.busy || typeof token !== "string") {
throw new ValidationError("containerFileTransferExpired");
}
transfer.timer.refresh();
if (action === "cancel") {
this.release(token);
return {};
}
if (action === "finish") {
if (transfer.type !== "upload" || transfer.offset !== transfer.data.length) {
throw new ValidationError("containerFileInvalidRequest");
}
transfer.busy = true;
try {
await this.requireRunning(transfer.id);
await this.run(transfer.id, write, [ transfer.path, transfer.expected || "", String(transfer.data.length) ], transfer.data);
return {};
} finally {
this.release(token);
}
}
if (args.offset !== transfer.offset || transfer.offset >= transfer.data.length) {
throw new ValidationError("containerFileInvalidRequest");
}
const end = Math.min(transfer.offset + fileChunkBytes, transfer.data.length);
if (transfer.type === "download") {
const data = transfer.data.subarray(transfer.offset, end);
transfer.offset = end;
if (end === transfer.data.length) {
this.release(token);
}
return { data };
}
if (!Buffer.isBuffer(args.data) || args.data.length !== end - transfer.offset) {
throw new ValidationError("containerFileInvalidRequest");
}
args.data.copy(transfer.data, transfer.offset);
transfer.offset = end;
return {};
}
}

View File

@ -0,0 +1,37 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { ValidationError } from "./util-server";
const exec = promisify(execFile);
const idPattern = /^[0-9a-f]{64}$/;
export function containerId(id: unknown): string {
if (typeof id !== "string" || !idPattern.test(id)) {
throw new ValidationError("containerInvalidId");
}
return id;
}
export function docker(args: string[], timeout = 15000, maxBuffer = 4 * 1024 * 1024) {
return exec("docker", args, { timeout,
maxBuffer,
encoding: "utf8",
windowsHide: true });
}
interface ContainerRow {
id: string;
name: string;
image: string;
state: string;
project: string;
}
const format = "{\"id\":{{json .ID}},\"name\":{{json .Names}},\"image\":{{json .Image}},\"state\":{{json .State}},\"project\":{{json (.Label \"com.docker.compose.project\")}}}";
export class ContainerManagement {
async list(): Promise<ContainerRow[]> {
const { stdout } = await docker([ "container", "ls", "--all", "--no-trunc", "--format", format ]);
return stdout.trim().split(/\r?\n/).filter(Boolean).map(row => JSON.parse(row) as ContainerRow);
}
}

303
backend/docker-resources.ts Normal file
View File

@ -0,0 +1,303 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { ValidationError } from "./util-server";
const exec = promisify(execFile);
const imageId = /^sha256:[0-9a-f]{64}$/;
const volumeName = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;
const tagName = /^[a-zA-Z0-9][a-zA-Z0-9./:_-]*:[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/;
interface ContainerUsage {
id: string;
name: string;
image: string;
reference: string;
state: string;
mounts: Array<{ Type: string; Name?: string; Source: string }> | null;
}
interface Platform {
os: string;
architecture: string;
variant?: string;
}
interface Image {
id: string;
tags: string[] | null;
created: string | null;
size: number | null;
os: string;
arch: string;
variant?: string;
descriptor?: { digest: string; mediaType: string; platform?: Platform };
}
interface Volume {
name: string;
driver: string;
created: string | null;
}
type TagStatus = "current" | "updateAvailable" | "unknown";
interface Manifest {
Descriptor?: { digest: string; platform?: Platform };
SchemaV2Manifest?: { config?: { digest: string } };
OCIManifest?: { config?: { digest: string } };
}
const containerFields = "{\"id\":{{json .Id}},\"name\":{{json .Name}},\"image\":{{json .Image}},\"reference\":{{json .Config.Image}},\"state\":{{json .State.Status}},\"mounts\":{{json .Mounts}}}";
const imageFields = "{\"id\":{{json .Id}},\"tags\":{{json (index . \"RepoTags\")}},\"created\":{{json (index . \"Created\")}},\"size\":{{json (index . \"Size\")}},\"os\":{{json (index . \"Os\")}},\"arch\":{{json (index . \"Architecture\")}},\"variant\":{{json (index . \"Variant\")}},\"descriptor\":{{json (index . \"Descriptor\")}}}";
const volumeFields = "{\"name\":{{json .Name}},\"driver\":{{json .Driver}},\"created\":{{json (index . \"CreatedAt\")}}}";
async function docker(args: string[], timeout = 15000, allowMissing = false): Promise<string> {
try {
const { stdout } = await exec("docker", args, {
encoding: "utf8",
timeout,
maxBuffer: 8 * 1024 * 1024,
windowsHide: true,
});
return stdout.trim();
} catch (error) {
const result = error as { stderr?: string; stdout?: string };
const messages = lines(result.stderr?.trim() ?? "");
if (allowMissing && messages.length && messages.every(line => /^Error response from daemon: No such (image|volume):/.test(line))) {
return result.stdout?.trim() ?? "";
}
throw error;
}
}
function lines(value: string) {
return value ? value.split(/\r?\n/) : [];
}
async function inspect<T>(kind: string, format: string, ids: string[], allowMissing = false): Promise<T[]> {
const result: T[] = [];
// Bound command-line length on hosts with many Docker resources.
for (let offset = 0; offset < ids.length; offset += 50) {
const output = await docker([ kind, "inspect", "--format", format, "--", ...ids.slice(offset, offset + 50) ], 15000, allowMissing);
result.push(...lines(output).map(line => JSON.parse(line) as T));
}
return result;
}
async function containers() {
const ids = lines(await docker([ "container", "ls", "--all", "--quiet", "--no-trunc" ]));
return inspect<ContainerUsage>("container", containerFields, ids);
}
function displayUsage(container: ContainerUsage) {
return {
id: container.id,
name: container.name.replace(/^\//, ""),
state: container.state,
reference: container.reference,
};
}
function canonicalTag(reference: string) {
if (reference.includes("@")) {
return reference;
}
const slash = reference.indexOf("/");
const first = reference.slice(0, slash);
const tag = reference.lastIndexOf(":") > reference.lastIndexOf("/") ? reference : reference + ":latest";
if (slash < 0) {
return "docker.io/library/" + tag;
}
if (/^(docker\.io|index\.docker\.io|registry-1\.docker\.io)$/.test(first)) {
const name = tag.slice(slash + 1);
return "docker.io/" + (name.includes("/") ? name : "library/" + name);
}
if (first === "localhost" || first.includes(".") || first.includes(":")) {
return tag;
}
return "docker.io/" + tag;
}
function usesVolume(container: ContainerUsage, name: string) {
return container.mounts?.some(mount => mount.Type === "volume" && mount.Name === name);
}
function usesImage(container: ContainerUsage, id: string) {
return container.image === id || container.mounts?.some(mount => mount.Type === "image" && mount.Source === id);
}
export class DockerResources {
private imagesRequest?: ReturnType<DockerResources["loadImages"]>;
private volumesRequest?: ReturnType<DockerResources["loadVolumes"]>;
private checkingRegistry = false;
private readonly checks = new Map<string, { status: TagStatus; expires: number }>();
listImages() {
this.imagesRequest ??= this.loadImages().finally(() => {
this.imagesRequest = undefined;
});
return this.imagesRequest;
}
listVolumes() {
this.volumesRequest ??= this.loadVolumes().finally(() => {
this.volumesRequest = undefined;
});
return this.volumesRequest;
}
private async loadImages() {
const [ usage, tagged, dangling ] = await Promise.all([
containers(),
docker([ "image", "ls", "--quiet", "--no-trunc" ]),
docker([ "image", "ls", "--quiet", "--no-trunc", "--filter", "dangling=true" ]),
]);
const ids = Array.from(new Set([ ...lines(tagged), ...lines(dangling), ...usage.map(container => container.image) ]));
const images = await inspect<Image>("image", imageFields, ids, true);
const inspected = new Set(images.map(image => image.id));
// Containerd may keep the content of an untagged image only through its container.
for (const id of new Set(usage.map(container => container.image))) {
if (imageId.test(id) && !inspected.has(id)) {
images.push({ id,
tags: [],
created: null,
size: null,
os: "",
arch: "" });
}
}
const imagesByTag = new Map(images.flatMap(image => (image.tags ?? []).map(tag => [ canonicalTag(tag), image.id ] as const)));
return images.map(image => ({
id: image.id,
tags: image.tags ?? [],
created: image.created,
size: image.size,
referenceOnly: !inspected.has(image.id),
platform: [ image.os, image.arch, image.variant ].filter(Boolean).join("/"),
checks: Object.fromEntries((image.tags ?? []).flatMap(tag => {
const check = this.checks.get(image.id + " " + tag);
return check && check.expires > Date.now() ? [[ tag, check.status ]] : [];
})),
containers: usage.filter(container => usesImage(container, image.id)).map(container => {
const current = imagesByTag.get(canonicalTag(container.reference));
return {
...displayUsage(container),
differentTagImage: Boolean(current && current !== container.image),
};
}),
}));
}
private async loadVolumes() {
const [ usage, listed ] = await Promise.all([ containers(), docker([ "volume", "ls", "--quiet" ]) ]);
const volumes = await inspect<Volume>("volume", volumeFields, lines(listed), true);
return volumes.map(volume => ({
...volume,
containers: usage.filter(container => usesVolume(container, volume.name)).map(displayUsage),
}));
}
/** Compare the selected tag for this platform without pulling layers. */
async checkImage(id: unknown, tag: unknown) {
const image = await this.getTaggedImage(id, tag);
if (this.checkingRegistry) {
throw new ValidationError("resourceRegistryBusy");
}
this.checkingRegistry = true;
try {
const status = await this.compareTag(image, String(tag));
const key = image.id + " " + tag;
this.checks.delete(key);
this.checks.set(key, { status,
expires: Date.now() + 15 * 60 * 1000 });
if (this.checks.size > 512) {
const oldest = this.checks.keys().next().value;
if (oldest) {
this.checks.delete(oldest);
}
}
return status;
} finally {
this.checkingRegistry = false;
}
}
private async compareTag(image: Image, tag: string): Promise<TagStatus> {
try {
const platform = image.descriptor?.platform ?? {
os: image.os,
architecture: image.arch,
variant: image.variant,
};
let local = image.id;
if (/index|manifest\.list/.test(image.descriptor?.mediaType ?? "")) {
const format = [ platform.os, platform.architecture, platform.variant ].filter(Boolean).join("/");
local = await docker([ "image", "inspect", "--platform", format, "--format", "{{.Id}}", "--", image.id ]);
}
const raw = await docker([ "manifest", "inspect", "--verbose", "--", tag ], 45000);
const parsed = JSON.parse(raw) as Manifest | Manifest[];
const matches = (Array.isArray(parsed) ? parsed : [ parsed ]).filter(entry => {
const remote = entry.Descriptor?.platform;
return remote?.os === platform.os && remote.architecture === platform.architecture
&& (!platform.variant || !remote.variant || platform.variant === remote.variant);
});
if (matches.length !== 1) {
return "unknown";
}
const match = matches[0];
const digest = match.Descriptor?.digest;
const config = (match.OCIManifest ?? match.SchemaV2Manifest)?.config?.digest;
if (!digest || !imageId.test(digest) || !imageId.test(local)) {
return "unknown";
}
return local === digest || local === config ? "current" : "updateAvailable";
} catch {
return "unknown";
}
}
async removeImage(id: unknown, tag: unknown) {
if (typeof id !== "string" || !imageId.test(id) || typeof tag !== "string") {
throw new ValidationError("resourceInvalidSelection");
}
if ((await containers()).some(container => usesImage(container, id))) {
throw new ValidationError("resourceInUse");
}
if (tag) {
await this.getTaggedImage(id, tag);
} else {
const [ image ] = await inspect<Image>("image", imageFields, [ id ]);
if (image.tags?.length) {
throw new ValidationError("resourceChanged");
}
}
// Docker performs its own usage check as part of the removal.
await docker([ "image", "rm", "--no-prune", "--", tag || id ]);
}
async removeVolume(name: unknown, created: unknown) {
if (typeof name !== "string" || !volumeName.test(name) || (typeof created !== "string" && created !== null)) {
throw new ValidationError("resourceInvalidSelection");
}
const [ volume ] = await inspect<Volume>("volume", volumeFields, [ name ]);
if (volume.created !== created) {
throw new ValidationError("resourceChanged");
}
if ((await containers()).some(container => usesVolume(container, name))) {
throw new ValidationError("resourceInUse");
}
await docker([ "volume", "rm", "--", name ]);
}
private async getTaggedImage(id: unknown, tag: unknown) {
if (typeof id !== "string" || !imageId.test(id) || typeof tag !== "string" || !tagName.test(tag) || tag.length > 512) {
throw new ValidationError("resourceInvalidSelection");
}
const [ image ] = await inspect<Image>("image", imageFields, [ tag ]);
if (image.id !== id || !image.tags?.includes(tag)) {
throw new ValidationError("resourceChanged");
}
return image;
}
}

View File

@ -15,7 +15,6 @@ import { Socket } from "socket.io";
import { MainSocketHandler } from "./socket-handlers/main-socket-handler";
import { SocketHandler } from "./socket-handler";
import { Settings } from "./settings";
import checkVersion from "./check-version";
import dayjs from "dayjs";
import { R } from "redbean-node";
import { genSecret, isDev, LooseObject } from "../common/util-common";
@ -23,6 +22,12 @@ import { generatePasswordHash } from "./password-hash";
import { Bean } from "redbean-node/dist/bean";
import { Arguments, Config, DockgeSocket } from "./util-server";
import { DockerSocketHandler } from "./agent-socket-handlers/docker-socket-handler";
import { ResourceSocketHandler } from "./agent-socket-handlers/resource-socket-handler";
import { DockerResources } from "./docker-resources";
import { ContainerManagement } from "./container-management";
import { ContainerFileExplorer } from "./container-file-explorer";
import { ContainerManagementSocketHandler } from "./agent-socket-handlers/container-management-socket-handler";
import { ResourceCleanup } from "./resource-cleanup";
import expressStaticGzip from "express-static-gzip";
import path from "path";
import { TerminalSocketHandler } from "./agent-socket-handlers/terminal-socket-handler";
@ -70,6 +75,8 @@ export class DockgeServer {
*/
agentSocketHandlerList : AgentSocketHandler[] = [
new DockerSocketHandler(),
new ContainerManagementSocketHandler(),
new ResourceSocketHandler(),
new TerminalSocketHandler(),
];
@ -84,6 +91,10 @@ export class DockgeServer {
stacksDir : string = "";
stackAutoUpdate = new StackAutoUpdate(this);
dockerResources = new DockerResources();
containerManagement = new ContainerManagement();
containerFileExplorer = new ContainerFileExplorer();
resourceCleanup = new ResourceCleanup();
imageVulnerabilityScan = new ImageVulnerabilityScan(this);
/**
@ -93,7 +104,7 @@ export class DockgeServer {
// Catch unexpected errors here
let unexpectedErrorHandler = (error : unknown) => {
console.trace(error);
console.error("If you keep encountering errors, please report to https://github.com/louislam/dockge");
console.error("If you keep encountering errors, contact Weapie, the maintainer of this Dockge fork.");
};
process.addListener("unhandledRejection", unexpectedErrorHandler);
process.addListener("uncaughtException", unexpectedErrorHandler);
@ -414,8 +425,9 @@ export class DockgeServer {
this.sendStackList(true);
});
checkVersion.startInterval();
this.stackAutoUpdate.start();
this.resourceCleanup.start();
this.imageVulnerabilityScan.startScannerUpdates();
});
gracefulShutdown(this.httpServer, {
@ -437,18 +449,15 @@ export class DockgeServer {
*/
async sendInfo(socket : Socket, hideVersion = false) {
let versionProperty;
let latestVersionProperty;
let isContainer;
if (!hideVersion) {
versionProperty = packageJSON.version;
latestVersionProperty = checkVersion.latestVersion;
isContainer = (process.env.DOCKGE_IS_CONTAINER === "1");
}
socket.emit("info", {
version: versionProperty,
latestVersion: latestVersionProperty,
isContainer,
primaryHostname: await Settings.get("primaryHostname"),
//serverTimezone: await this.getTimezone(),
@ -694,6 +703,7 @@ export class DockgeServer {
// TODO: Close all terminals?
this.stackAutoUpdate.stop();
this.resourceCleanup.stop();
await this.imageVulnerabilityScan.stop();
await Database.close();
Settings.stopCacheCleaner();

165
backend/grype-updater.ts Normal file
View File

@ -0,0 +1,165 @@
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import { createWriteStream, promises as fs } from "node:fs";
import path from "node:path";
import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import { promisify } from "node:util";
import { gt, valid } from "semver";
import { log } from "./log";
const exec = promisify(execFile);
// Node 22 provides AbortSignal.any. The project's ambient Node types predate it.
const signalClass = AbortSignal as typeof AbortSignal & { any(signals: AbortSignal[]): AbortSignal };
const releaseAPI = "https://api.github.com/repos/anchore/grype/releases/latest";
const releaseBase = "https://github.com/anchore/grype/releases/download";
const interval = 6 * 60 * 60 * 1000;
const maxArchiveBytes = 100 * 1024 * 1024;
interface Release {
tag_name: string;
assets: Array<{ name: string; digest: string; size: number }>;
}
export class GrypeUpdater {
private readonly override = process.env.DOCKGE_GRYPE_PATH;
private readonly shutdown = new AbortController();
private readonly architecture = process.platform === "linux" ? { x64: "amd64",
arm64: "arm64" }[process.arch as "x64" | "arm64"] : undefined;
private current = "grype";
private pending?: Promise<void>;
private timer?: NodeJS.Timeout;
private nextCheck = 0;
constructor(private readonly directory: string) {}
start() {
void this.executable();
this.timer ??= setInterval(() => void this.executable(), 15 * 60 * 1000).unref();
}
async stop() {
clearInterval(this.timer);
this.shutdown.abort();
await this.pending;
}
async executable() {
if (this.override || !this.architecture || this.shutdown.signal.aborted) {
return this.override || this.current;
}
if (!this.pending && Date.now() >= this.nextCheck) {
this.pending = this.refresh(this.architecture).then(() => {
this.nextCheck = Date.now() + interval;
}).catch(() => {
this.nextCheck = Date.now() + 15 * 60 * 1000;
if (!this.shutdown.signal.aborted) {
log.warn("grype-update", "Could not refresh Grype from Anchore releases");
}
}).finally(() => {
this.pending = undefined;
});
}
await this.pending;
return this.current;
}
private async version(binary: string): Promise<string | null> {
try {
const { stdout } = await exec(binary, [ "version", "-o", "json" ], {
env: { ...process.env,
GRYPE_CHECK_FOR_APP_UPDATE: "false" },
signal: this.shutdown.signal,
timeout: 5000,
maxBuffer: 64 * 1024,
});
return valid(JSON.parse(stdout).version);
} catch {
return null;
}
}
private async refresh(arch: string) {
const installed = path.join(this.directory, "grype");
const [ bundled, cached ] = await Promise.all([ this.version("grype"), this.version(installed) ]);
const useCached = cached && (!bundled || gt(cached, bundled));
this.current = useCached ? installed : "grype";
const currentVersion = useCached ? cached : bundled;
const response = await fetch(releaseAPI, {
signal: signalClass.any([ this.shutdown.signal, AbortSignal.timeout(10000) ]),
headers: { Accept: "application/vnd.github+json",
"User-Agent": "Dockge-Grype-Updater" },
});
if (!response.ok) {
throw new Error("Could not retrieve Grype release");
}
const release = await response.json() as Release;
const tag = release.tag_name;
const version = /^v\d+\.\d+\.\d+$/.test(tag) ? valid(tag) : null;
if (!version) {
throw new Error("Invalid Grype release tag");
}
if (currentVersion && !gt(version, currentVersion)) {
return;
}
const filename = `grype_${version}_linux_${arch}.tar.gz`;
const asset = release.assets?.find(asset => asset.name === filename);
if (!asset || !/^sha256:[a-f0-9]{64}$/.test(asset.digest)
|| !Number.isSafeInteger(asset.size) || asset.size < 1 || asset.size > maxArchiveBytes) {
throw new Error("Missing Grype release checksum");
}
await fs.mkdir(this.directory, { recursive: true });
const temp = await fs.mkdtemp(path.join(this.directory, ".install-"));
try {
const archive = path.join(temp, "archive.tar.gz");
await this.download(`${releaseBase}/${tag}/${filename}`, archive, asset);
const binary = path.join(temp, "grype");
const options = { signal: this.shutdown.signal,
timeout: 15000,
maxBuffer: 150 * 1024 * 1024,
encoding: "buffer" as const };
const { stdout } = await exec("tar", [ "-xOzf", archive, "grype" ], options);
await fs.writeFile(binary, stdout, { mode: 0o755 });
if (await this.version(binary) !== version) {
throw new Error("Downloaded Grype could not be verified");
}
const license = await exec("tar", [ "-xOzf", archive, "LICENSE" ], options);
await fs.writeFile(path.join(temp, "LICENSE"), license.stdout);
await fs.rename(path.join(temp, "LICENSE"), path.join(this.directory, "LICENSE"));
await fs.rename(binary, installed);
this.current = installed;
log.info("grype-update", `Installed Grype ${version}`);
} finally {
await fs.rm(temp, { recursive: true,
force: true });
}
}
private async download(url: string, archive: string, asset: { size: number; digest: string }) {
const signal = signalClass.any([ this.shutdown.signal, AbortSignal.timeout(90000) ]);
const response = await fetch(url, { signal });
if (!response.ok || !response.body) {
throw new Error("Grype download failed");
}
const hash = createHash("sha256");
let size = 0;
const verify = new Transform({
transform(chunk: Buffer, encoding, callback) {
size += chunk.length;
if (size > asset.size) {
callback(new Error("Grype archive exceeds release asset size"));
return;
}
hash.update(chunk);
callback(null, chunk);
},
});
await pipeline(Readable.fromWeb(response.body as unknown as import("node:stream/web").ReadableStream<Uint8Array>), verify, createWriteStream(archive, { flags: "wx" }), { signal });
if (size !== asset.size || `sha256:${hash.digest("hex")}` !== asset.digest) {
throw new Error("Grype archive checksum mismatch");
}
}
}

View File

@ -1,3 +1,4 @@
import { GrypeUpdater } from "./grype-updater";
import { execFile, spawn } from "node:child_process";
import { randomUUID } from "node:crypto";
import { createWriteStream, promises as fs } from "node:fs";
@ -20,6 +21,7 @@ const maxImages = 20;
const maxReports = 8;
const maxFindings = 500;
const pageSize = 25;
const databaseTimeout = 15 * 60 * 1000;
const imageIdPattern = /^sha256:[a-f0-9]{64}$/;
const inspectFields = [
"\"id\":{{json .Image}}",
@ -60,6 +62,7 @@ interface ScanReport {
startedAt: string;
finishedAt?: string;
error?: string;
preparingDatabase?: boolean;
images: ImageScan[];
}
@ -158,7 +161,7 @@ function normalizeFindings(output: string) {
}
export class ImageVulnerabilityScan {
private readonly scanner = process.env.DOCKGE_GRYPE_PATH || "grype";
private updater?: GrypeUpdater;
private readonly reports = new Map<string, ScanReport>();
private readonly shutdown = new AbortController();
private active?: ScanReport;
@ -231,9 +234,19 @@ export class ImageVulnerabilityScan {
this.reports.delete(stackName);
}
private get scanner() {
this.updater ??= new GrypeUpdater(path.resolve(this.server.config.dataDir, "grype-bin"));
return this.updater;
}
startScannerUpdates() {
this.scanner.start();
}
/** Abort outstanding commands as Dockge shuts down. */
async stop() {
this.shutdown.abort();
await this.updater?.stop();
await this.activeRun;
}
@ -242,7 +255,12 @@ export class ImageVulnerabilityScan {
try {
report.images = await this.discoverImages(stack);
if (report.images.length) {
await this.runGrype([ "version" ], path.resolve(this.server.config.dataDir), 5000);
report.preparingDatabase = true;
try {
await this.prepareDatabase();
} finally {
report.preparingDatabase = false;
}
}
for (const image of report.images) {
@ -394,10 +412,28 @@ export class ImageVulnerabilityScan {
return stdout.trim();
}
/** Invoke a local Grype binary against an archive, with a persistent DB cache. */
/** Update once per report and use a valid cached database if the update fails. */
private async prepareDatabase() {
const cwd = os.tmpdir();
try {
await this.runGrype([ "db", "update" ], cwd, databaseTimeout);
} catch (error) {
if (this.shutdown.signal.aborted || error instanceof ValidationError) {
throw error;
}
this.reportError(error, "imageScanDatabaseUnavailable");
try {
await this.runGrype([ "db", "status" ], cwd, 60 * 1000);
} catch {
throw new ValidationError("imageScanDatabaseUnavailable");
}
}
}
/** Invoke Grype with the same cache for the database update and the image scans. */
private async runGrype(args: string[], cwd: string, timeout: number): Promise<string> {
try {
const { stdout } = await exec(this.scanner, args, {
const { stdout } = await exec(await this.scanner.executable(), args, {
cwd,
timeout,
maxBuffer: 32 * 1024 * 1024,
@ -405,8 +441,10 @@ export class ImageVulnerabilityScan {
windowsHide: true,
env: {
...process.env,
GRYPE_DB_CACHE_DIR: path.resolve(this.server.config.dataDir, "grype-db"),
GRYPE_DB_CACHE_DIR: path.resolve(process.env.GRYPE_DB_CACHE_DIR || path.join(this.server.config.dataDir, "grype-db")),
GRYPE_CHECK_FOR_APP_UPDATE: "false",
GRYPE_DB_AUTO_UPDATE: "false",
GRYPE_DB_UPDATE_DOWNLOAD_TIMEOUT: process.env.GRYPE_DB_UPDATE_DOWNLOAD_TIMEOUT || "10m",
TMPDIR: cwd,
TMP: cwd,
TEMP: cwd,
@ -429,7 +467,8 @@ export class ImageVulnerabilityScan {
if (error instanceof ValidationError) {
return error.message;
}
const code = (error as NodeJS.ErrnoException)?.code ?? "unknown";
const failure = error as (NodeJS.ErrnoException & { killed?: boolean }) | undefined;
const code = failure?.killed ? "timeout" : failure?.code ?? "unknown";
log.warn("image-scan", `${fallback} (${code})`);
return fallback;
}

165
backend/resource-cleanup.ts Normal file
View File

@ -0,0 +1,165 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { Cron } from "croner";
import { log } from "./log";
import { Settings } from "./settings";
import { ValidationError } from "./util-server";
const exec = promisify(execFile);
const kinds = [ "images", "volumes" ] as const;
type Kind = typeof kinds[number];
const defaults = { enabled: false,
time: "04:00",
timezone: "UTC" };
type Schedule = typeof defaults;
function resourceKind(value: unknown): Kind {
if (value !== "images" && value !== "volumes") {
throw new ValidationError("resourceInvalidSelection");
}
return value;
}
function validSchedule(value: unknown): value is Schedule {
const schedule = value as Partial<Schedule> | null;
if (typeof schedule?.enabled !== "boolean" || typeof schedule.time !== "string"
|| !/^([01]\d|2[0-3]):[0-5]\d$/.test(schedule.time)
|| typeof schedule.timezone !== "string" || !/^[A-Za-z][A-Za-z0-9_+/-]{0,99}$/.test(schedule.timezone)) {
return false;
}
try {
new Intl.DateTimeFormat("en-CA", { timeZone: schedule.timezone });
return true;
} catch {
return false;
}
}
export class ResourceCleanup {
private readonly jobs = new Map<Kind, Cron>();
private readonly running = new Set<Kind>();
private readonly saving = new Set<Kind>();
private readonly shutdown = new AbortController();
private initialization?: Promise<void>;
start() {
this.initialization ??= this.initialize();
}
stop() {
this.shutdown.abort();
this.jobs.forEach(job => job.stop());
}
private async initialize() {
for (const kind of kinds) {
try {
this.schedule(kind, await this.read(kind));
} catch {
log.warn("resource-cleanup", `Could not load ${kind} schedule`);
}
}
}
private async read(kind: Kind): Promise<Schedule> {
const value = await Settings.get(`resourceCleanup:${kind}`, false);
return validSchedule(value) ? value : { ...defaults };
}
async status(value: unknown) {
const kind = resourceKind(value);
await this.initialization;
const schedule = await this.read(kind);
return {
...schedule,
nextRun: this.jobs.get(kind)?.nextRun()?.toISOString(),
lastRun: await Settings.get(`resourceCleanupRun:${kind}`, false) || null,
};
}
async set(value: unknown, schedule: unknown) {
const kind = resourceKind(value);
await this.initialization;
if (!validSchedule(schedule)) {
throw new ValidationError("resourceCleanupInvalidSchedule");
}
if (this.saving.has(kind)) {
throw new ValidationError("resourceCleanupBusy");
}
this.saving.add(kind);
try {
const { enabled, time, timezone } = schedule;
await Settings.set(`resourceCleanup:${kind}`, { enabled,
time,
timezone });
this.schedule(kind, schedule);
return await this.status(kind);
} finally {
this.saving.delete(kind);
}
}
private schedule(kind: Kind, schedule: Schedule) {
this.jobs.get(kind)?.stop();
this.jobs.delete(kind);
if (!schedule.enabled || this.shutdown.signal.aborted) {
return;
}
const [ hours, minutes ] = schedule.time.split(":").map(Number);
const job = new Cron(`${minutes} ${hours} * * *`, {
timezone: schedule.timezone,
protect: true,
}, () => this.runScheduled(kind, schedule, job));
this.jobs.set(kind, job);
}
private async runScheduled(kind: Kind, schedule: Schedule, job: Cron) {
const date = new Date();
const day = date.toLocaleDateString("en-CA", { timeZone: schedule.timezone });
const key = `resourceCleanupRun:${kind}`;
try {
const previous = await Settings.get(key, false);
const current = await this.read(kind);
if (this.jobs.get(kind) !== job || previous?.day === day || !current.enabled || current.time !== schedule.time
|| current.timezone !== schedule.timezone || this.shutdown.signal.aborted) {
return;
}
await Settings.set(key, { at: date.toISOString(),
day,
result: "started" });
let result = "success";
try {
await this.prune(kind);
} catch {
result = "failed";
}
if (!this.shutdown.signal.aborted) {
await Settings.set(key, { at: date.toISOString(),
day,
result });
log.info("resource-cleanup", `${kind}: ${result}`);
}
} catch {
log.warn("resource-cleanup", `Could not run ${kind} schedule`);
}
}
async prune(value: unknown) {
const kind = resourceKind(value);
if (this.running.has(kind) || this.shutdown.signal.aborted) {
throw new ValidationError("resourceCleanupBusy");
}
this.running.add(kind);
try {
// The Docker daemon determines which resources are currently unreferenced.
await exec("docker", [ kind === "images" ? "image" : "volume", "prune", "--all", "--force" ], {
timeout: 120000,
maxBuffer: 8 * 1024 * 1024,
signal: this.shutdown.signal,
windowsHide: true,
});
} finally {
this.running.delete(kind);
}
}
}

View File

@ -22,6 +22,9 @@ export class AgentProxySocketHandler extends SocketHandler {
}
if (endpoint === ALL_ENDPOINTS) { // Send to all endpoints
if ([ "containerFiles", "listHostContainers" ].includes(eventName)) {
throw new Error("containerActionUnavailable");
}
log.debug("agent", "Sending to all endpoints: " + eventName);
socket.instanceManager.emitToAllEndpoints(eventName, ...args);

View File

@ -12,18 +12,82 @@ import { ValidationError } from "./util-server";
const exec = promisify(execFile);
const policyFile = ".dockge-auto-update.json";
const dockgeImage = /(?:^|\/)louislam\/dockge(?:[:@]|$)/i;
const dockgeImage = /(?:^|\/)(?:louislam\/dockge|dockge:local)(?:[:@]|$)/i;
const stackName = /^[a-z0-9_-]+$/;
type Outcome = "updated" | "unchanged" | "skipped" | "failed";
const outcomes: Outcome[] = [ "updated", "unchanged", "skipped", "failed" ];
type Outcome = "updated" | "unchanged" | "waiting" | "skipped" | "failed";
const outcomes: Outcome[] = [ "updated", "unchanged", "waiting", "skipped", "failed" ];
interface Policy {
interface Schedule {
enabled: boolean;
time: string;
timezone: string;
delayHours: number;
}
interface PendingImage {
service: string;
image: string;
id: string;
since: string;
}
interface Policy extends Schedule {
lastScheduledDay?: string;
lastRun?: {
at: string;
result: Outcome;
};
pending: PendingImage[];
}
const defaults: Schedule = {
enabled: false,
time: "04:00",
timezone: "UTC",
delayHours: 0,
};
const clockTime = /^([01][0-9]|2[0-3]):[0-5][0-9]$/;
const hourMs = 60 * 60 * 1000;
function validTimezone(timezone: unknown): timezone is string {
if (typeof timezone !== "string" || timezone.length > 100 || !/^[A-Za-z][A-Za-z0-9_+/-]*$/.test(timezone)) {
return false;
}
try {
new Intl.DateTimeFormat("en-CA", { timeZone: timezone });
return true;
} catch {
return false;
}
}
function validDelay(value: unknown): value is number {
return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 2160;
}
function validDate(value: unknown): value is string {
return typeof value === "string" && Number.isFinite(Date.parse(value));
}
function localDay(timezone: string, date: Date): string {
return new Intl.DateTimeFormat("en-CA", {
timeZone: timezone,
year: "numeric",
month: "2-digit",
day: "2-digit",
}).format(date);
}
function nextRun(policy: Schedule, after: Date) {
const [ hours, minutes ] = policy.time.split(":").map(Number);
const cron = new Cron(`${minutes} ${hours} * * *`, { timezone: policy.timezone,
paused: true });
try {
return cron.nextRun(after);
} finally {
cron.stop();
}
}
interface ContainerSummary {
@ -62,26 +126,28 @@ const inspectFormat = `{${inspectFields.join(",")}}`;
export class StackAutoUpdate {
private schedule?: Cron;
private runInProgress = false;
private readonly due = new Map<string, Date>();
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 * * *", {
this.schedule = new Cron("0 * * * * *", {
timezone: "UTC",
protect: true,
}, () => this.run());
}, () => this.collectDue());
}
/** Stop scheduling and terminate commands during application shutdown. */
stop() {
this.schedule?.stop();
this.due.clear();
this.shutdown.abort();
}
/** Return an absent policy for stacks that cannot be scheduled. */
async getPolicy(stack: Stack): Promise<Policy | undefined> {
private async readPolicy(stack: Stack): Promise<Policy | undefined> {
if (!stackName.test(stack.name) || stack.name === "dockge") {
return;
}
@ -98,7 +164,18 @@ export class StackAutoUpdate {
}
const policy = JSON.parse(await fs.readFile(file, "utf8"));
const lastRun = policy?.lastRun;
const validPolicy: Policy = { enabled: policy?.enabled === true };
const validPolicy: Policy = {
enabled: policy?.enabled === true,
time: typeof policy?.time === "string" && clockTime.test(policy.time) ? policy.time : defaults.time,
timezone: validTimezone(policy?.timezone) ? policy.timezone : defaults.timezone,
delayHours: validDelay(policy?.delayHours) ? policy.delayHours : defaults.delayHours,
pending: Array.isArray(policy?.pending) ? policy.pending.filter((entry: PendingImage) =>
typeof entry?.service === "string" && typeof entry.image === "string"
&& typeof entry.id === "string" && /^sha256:[a-f0-9]{64}$/.test(entry.id) && validDate(entry.since)) : [],
};
if (typeof policy?.lastScheduledDay === "string" && /^\d{4}-\d{2}-\d{2}$/.test(policy.lastScheduledDay)) {
validPolicy.lastScheduledDay = policy.lastScheduledDay;
}
if (typeof lastRun?.at === "string" && Number.isFinite(Date.parse(lastRun.at)) && outcomes.includes(lastRun.result)) {
validPolicy.lastRun = {
at: lastRun.at,
@ -110,76 +187,121 @@ export class StackAutoUpdate {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
log.warn("auto-update", `Could not read policy for ${stack.name}`);
}
return { enabled: false };
return { ...defaults,
pending: [] };
}
}
/** 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.");
async getPolicy(stack: Stack) {
const policy = await this.readPolicy(stack);
return policy && this.publicPolicy(policy);
}
private publicPolicy(policy: Policy) {
let next = policy.enabled ? nextRun(policy, new Date()) : null;
if (next && localDay(policy.timezone, next) === policy.lastScheduledDay) {
next = nextRun(policy, next);
}
const policy = {
...current,
enabled,
return {
enabled: policy.enabled,
time: policy.time,
timezone: policy.timezone,
delayHours: policy.delayHours,
lastRun: policy.lastRun,
nextRun: next?.toISOString(),
pending: policy.pending.map(entry => ({
service: entry.service,
eligibleAt: new Date(Date.parse(entry.since) + policy.delayHours * hourMs).toISOString(),
})),
};
await this.writePolicy(stack, policy);
return policy;
}
/** Check each opted-in stack once per scheduled run. */
async run(): Promise<void> {
/** Save the schedule on the host running the stack. Boolean requests are used by older clients. */
async setPolicy(stack: Stack, settings: unknown) {
const current = await this.readPolicy(stack);
if (!current) {
throw new ValidationError("autoUpdateUnavailable");
}
if (typeof settings === "boolean") {
current.enabled = settings;
} else {
const schedule = settings as Partial<Schedule> | null;
if (typeof schedule?.enabled !== "boolean" || typeof schedule.time !== "string" || !clockTime.test(schedule.time)
|| !validTimezone(schedule.timezone) || !validDelay(schedule.delayHours)) {
throw new ValidationError("autoUpdateInvalidSchedule");
}
current.enabled = schedule.enabled;
current.time = schedule.time;
current.timezone = schedule.timezone;
current.delayHours = schedule.delayHours;
}
await this.writePolicy(stack, current);
return this.publicPolicy(current);
}
private isDue(policy: Policy, minute: Date) {
return policy.enabled && policy.lastScheduledDay !== localDay(policy.timezone, minute)
&& nextRun(policy, new Date(minute.getTime() - 1000))?.getTime() === minute.getTime();
}
/** Collect each minute separately so long pulls do not block other scheduled starts. */
private async collectDue() {
const minute = new Date(Math.floor(Date.now() / 60000) * 60000);
try {
const dirs = await fs.readdir(this.server.stacksDir, { withFileTypes: true });
for (const dir of dirs) {
if (!dir.isDirectory() || !stackName.test(dir.name) || dir.name === "dockge") {
continue;
}
const policy = await this.readPolicy(new Stack(this.server, dir.name));
if (policy && this.isDue(policy, minute)) {
this.due.set(dir.name, minute);
}
}
void this.runDue();
} catch (error) {
log.warn("auto-update", String(error));
}
}
private async runDue() {
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) {
for (const [ name, minute ] of this.due) {
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;
}
this.due.delete(name);
const stack = new Stack(this.server, name);
try {
await Stack.withOperation(this.server, dir.name, async () => {
const policy = await this.getPolicy(stack);
if (!policy?.enabled) {
await Stack.withOperation(this.server, name, async () => {
const policy = await this.readPolicy(stack);
if (!policy || !this.isDue(policy, minute)) {
return;
}
policy.lastScheduledDay = localDay(policy.timezone, minute);
await this.writePolicy(stack, policy);
let result: Outcome;
try {
result = await this.update(stack);
result = await this.update(stack, policy);
} 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,
},
});
policy.lastRun = {
at: new Date().toISOString(),
result,
};
await this.writePolicy(stack, policy);
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;
}
@ -201,7 +323,7 @@ export class StackAutoUpdate {
}
/** Pull and recreate only running services whose image actually changed. */
private async update(stack: Stack): Promise<Outcome> {
private async update(stack: Stack, policy: Policy): Promise<Outcome> {
const before = await this.getCandidates(stack);
if (before.size === 0) {
return "skipped";
@ -211,6 +333,9 @@ export class StackAutoUpdate {
const after = await this.getCandidates(stack);
const changed = new Map<string, Candidate>();
const pending = new Map(policy.pending.map(entry => [ entry.service, entry ]));
const waiting: PendingImage[] = [];
const observedAt = new Date();
let skipped = false;
for (const [ name, original ] of before) {
const current = after.get(name);
@ -223,21 +348,32 @@ export class StackAutoUpdate {
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)) {
if (current.imageIds.every(id => id === imageId)) {
continue;
}
const previous = pending.get(name);
const entry = previous?.id === imageId && previous.image === current.image ? previous : {
service: name,
image: current.image,
id: imageId,
since: observedAt.toISOString(),
};
waiting.push(entry);
if (observedAt.getTime() >= Date.parse(entry.since) + policy.delayHours * hourMs) {
changed.set(name, current);
}
}
policy.pending = waiting;
if (!changed.size) {
return skipped ? "skipped" : "unchanged";
return waiting.length ? "waiting" : (skipped ? "skipped" : "unchanged");
}
if (!(await this.getPolicy(stack))?.enabled) {
return "skipped";
}
// Keep first-seen times if deployment fails or the process stops partway through.
await this.writePolicy(stack, policy);
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()));
policy.pending = waiting.filter(entry => !changed.has(entry.service));
return "updated";
}

View File

@ -580,7 +580,7 @@ export class Stack {
let statusList = new Map<string, Array<object>>();
try {
let res = await childProcessAsync.spawn("docker", this.getComposeOptions("ps", "--format", "json"), {
let res = await childProcessAsync.spawn("docker", this.getComposeOptions("ps", "--no-trunc", "--orphans=false", "--format", "json"), {
cwd: this.path,
encoding: "utf-8",
});
@ -591,11 +591,13 @@ export class Stack {
let lines = res.stdout?.toString().split("\n");
const addLine = (obj: { Service: string, State: string, Name: string, Health: string }) => {
const addLine = (obj: { ID: string, Service: string, State: string, Name: string, Health: string }) => {
if (!statusList.has(obj.Service)) {
statusList.set(obj.Service, []);
}
statusList.get(obj.Service)?.push({
id: obj.ID,
state: obj.State,
status: obj.Health || obj.State,
name: obj.Name
});

View File

@ -0,0 +1,3 @@
export const fileChunkBytes = 256 * 1024;
export const maxContainerFileBytes = 32 * 1024 * 1024;
export const maxContainerTextBytes = 512 * 1024;

22
components.json Normal file
View File

@ -0,0 +1,22 @@
{
"$schema": "https://shadcn-vue.com/schema.json",
"style": "reka-nova",
"typescript": true,
"tailwind": {
"config": "",
"css": "frontend/src/styles/theme.css",
"baseColor": "mist",
"cssVariables": true
},
"iconLibrary": "phosphor",
"rtl": false,
"menuColor": "default",
"menuAccent": "bold",
"aliases": {
"components": "@/components",
"ui": "@/components/ui",
"utils": "@/lib/utils",
"lib": "@/lib",
"composables": "@/composables"
}
}

View File

@ -1,22 +1,21 @@
services:
dockge:
image: louislam/dockge:1
image: dockge:local
build:
context: .
dockerfile: docker/Dockerfile
target: release
restart: unless-stopped
ports:
# Host Port : Container Port
- 5001:5001
- "127.0.0.1:5001:5001"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- ./data:/app/data
# If you want to use private registries, you need to share the auth file with Dockge:
# - /root/.docker/:/root/.docker
# Stacks Directory
# ⚠️ READ IT CAREFULLY. If you did it wrong, your data could end up writing into a WRONG PATH.
# ⚠️ 1. FULL path only. No relative path (MUST)
# ⚠️ 2. Left Stacks Path === Right Stacks Path (MUST)
- /opt/stacks:/opt/stacks
- grype-db:/app/grype-db
# Stack paths must match inside Dockge and on the Docker host.
- "${DOCKGE_STACKS_DIR:-/opt/stacks}:${DOCKGE_STACKS_DIR:-/opt/stacks}"
environment:
# Tell Dockge where is your stacks directory
- DOCKGE_STACKS_DIR=/opt/stacks
DOCKGE_STACKS_DIR: "${DOCKGE_STACKS_DIR:-/opt/stacks}"
volumes:
grype-db:

View File

@ -1,3 +1,15 @@
############################################
# Build the Vue frontend
############################################
FROM louislam/dockge:base AS frontend
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --ignore-scripts
COPY common ./common
COPY frontend ./frontend
COPY tsconfig.json ./
RUN npm run build:frontend
############################################
# Healthcheck Binary
############################################
@ -20,7 +32,11 @@ ARG TARGETARCH
WORKDIR /app
COPY --chown=node:node --from=build_healthcheck /app/extra/healthcheck /app/extra/healthcheck
COPY --from=build /app/node_modules /app/node_modules
COPY --chown=node:node . .
COPY --chown=node:node backend ./backend
COPY --chown=node:node common ./common
COPY --chown=node:node extra ./extra
COPY --chown=node:node package.json package-lock.json tsconfig.json LICENSE ./
COPY --chown=node:node --from=frontend /app/frontend-dist ./frontend-dist
RUN mkdir ./data
# Grype is available upstream for the amd64 and arm64 images.
@ -46,8 +62,9 @@ RUN set -eu; \
# - https://github.com/sagemathinc/cocalc/issues/6963
# - https://github.com/microsoft/node-pty/issues/630#issuecomment-1987212447
ENV UV_USE_IO_URING=0
ENV GRYPE_DB_CACHE_DIR=/app/grype-db
VOLUME /app/data
VOLUME ["/app/data", "/app/grype-db"]
EXPOSE 5001
HEALTHCHECK --interval=60s --timeout=30s --start-period=60s --retries=5 CMD extra/healthcheck
ENTRYPOINT ["/usr/bin/dumb-init", "--"]

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

BIN
docs/images/images.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

BIN
docs/images/volumes.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

BIN
docs/images/wartung.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

View File

@ -1,42 +0,0 @@
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
export {}
declare module 'vue' {
export interface GlobalComponents {
About: typeof import('./src/components/settings/About.vue')['default']
Appearance: typeof import('./src/components/settings/Appearance.vue')['default']
ArrayInput: typeof import('./src/components/ArrayInput.vue')['default']
ArraySelect: typeof import('./src/components/ArraySelect.vue')['default']
BButton: typeof import('bootstrap-vue-next')['BButton']
BDropdown: typeof import('bootstrap-vue-next')['BDropdown']
BDropdownItem: typeof import('bootstrap-vue-next')['BDropdownItem']
BFormGroup: typeof import('bootstrap-vue-next')['BFormGroup']
BFormInput: typeof import('bootstrap-vue-next')['BFormInput']
BModal: typeof import('bootstrap-vue-next')['BModal']
Confirm: typeof import('./src/components/Confirm.vue')['default']
Container: typeof import('./src/components/Container.vue')['default']
DockerStat: typeof import('./src/components/DockerStat.vue')['default']
General: typeof import('./src/components/settings/General.vue')['default']
GlobalEnv: typeof import('./src/components/settings/GlobalEnv.vue')['default']
HiddenInput: typeof import('./src/components/HiddenInput.vue')['default']
ImageVulnerabilities: typeof import('./src/components/ImageVulnerabilities.vue')['default']
Login: typeof import('./src/components/Login.vue')['default']
NetworkInput: typeof import('./src/components/NetworkInput.vue')['default']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
Security: typeof import('./src/components/settings/Security.vue')['default']
StackConfigEditor: typeof import('./src/components/StackConfigEditor.vue')['default']
StackList: typeof import('./src/components/StackList.vue')['default']
StackListItem: typeof import('./src/components/StackListItem.vue')['default']
Terminal: typeof import('./src/components/Terminal.vue')['default']
TwoFADialog: typeof import('./src/components/TwoFADialog.vue')['default']
Uptime: typeof import('./src/components/Uptime.vue')['default']
}
export interface ComponentCustomProperties {
vBModal: typeof import('bootstrap-vue-next')['vBModal']
}
}

View File

@ -7,7 +7,7 @@
<link rel="icon" type="image/svg+xml" href="/icon.svg" />
<link rel="manifest" href="/manifest.json" />
<meta name="theme-color" id="theme-color" content="" />
<meta name="description" content="" />
<meta name="description" content="A fork of Dockge maintained by Weapie for managing Docker Compose stacks." />
<title>Dockge</title>
<style>
.noscript-message {

View File

@ -1,9 +1,4 @@
<template>
<router-view />
<Toaster :theme="$root.isDark ? 'dark' : 'light'" position="bottom-right" close-button />
</template>
<script>
export default {
};
</script>

View File

@ -0,0 +1,40 @@
<template>
<Dialog :open="modelValue" @update:open="$emit('update:modelValue', $event)">
<DialogContent :close-label="$t('Close')" :aria-describedby="undefined">
<form class="grid gap-4" @submit.prevent="confirm">
<DialogHeader>
<DialogTitle>{{ title }}</DialogTitle>
</DialogHeader>
<div class="grid gap-2 text-sm text-muted-foreground">
<slot />
</div>
<DialogFooter>
<DialogClose as-child>
<UiButton variant="outline">{{ $t("cancel") }}</UiButton>
</DialogClose>
<UiButton type="submit" :variant="destructive ? 'destructive' : 'default'">{{ action }}</UiButton>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</template>
<script>
export default {
props: {
modelValue: Boolean,
title: { type: String,
required: true },
action: { type: String,
required: true },
destructive: Boolean,
},
emits: [ "update:modelValue", "confirm" ],
methods: {
confirm() {
this.$emit("update:modelValue", false);
this.$emit("confirm");
},
},
};
</script>

View File

@ -1,23 +1,24 @@
<template>
<div>
<div v-if="valid">
<ul v-if="isArrayInited" class="list-group">
<li v-for="(value, index) in array" :key="index" class="list-group-item">
<input v-model="array[index]" type="text" class="no-bg domain-input" :placeholder="placeholder" />
<font-awesome-icon icon="times" class="action remove ms-2 me-3 text-danger" @click="remove(index)" />
</li>
</ul>
<button class="btn btn-normal btn-sm mt-3" @click="addField">{{ $t("addListItem", [ displayName ]) }}</button>
</div>
<div v-else>
{{ $t("LongSyntaxNotSupported") }}
</div>
<div v-if="valid" class="grid gap-2">
<ul v-if="isArrayInited" class="grid gap-1.5">
<li v-for="(_, index) in array" :key="index" class="flex items-center gap-1.5">
<UiInput v-model="array[index]" :aria-label="displayName" :placeholder="placeholder" />
<UiButton type="button" variant="ghost" size="icon" class="text-destructive" :aria-label="$t('removeEntry')" @click="remove(index)">
<AppIcon name="x" />
</UiButton>
</li>
</ul>
<UiButton type="button" variant="outline" size="sm" class="justify-self-start" @click="addField">
<AppIcon name="plus" /> {{ $t("addListItem", [ displayName ]) }}
</UiButton>
</div>
<p v-else class="text-sm text-muted-foreground">{{ $t("LongSyntaxNotSupported") }}</p>
</template>
<script>
export default {
inject: { containerEditor: { default: null },
composePage: {} },
props: {
name: {
type: String,
@ -65,15 +66,15 @@ export default {
service() {
if (this.objectType === "service") {
// Used in Container.vue
return this.$parent.$parent.service;
return this.containerEditor.service;
} else if (this.objectType === "x-dockge") {
if (!this.$parent.$parent.jsonConfig["x-dockge"]) {
if (!this.composePage.jsonConfig["x-dockge"]) {
return {};
}
// Used in Compose.vue
return this.$parent.$parent.jsonConfig["x-dockge"];
return this.composePage.jsonConfig["x-dockge"];
} else {
return {};
}
@ -103,8 +104,8 @@ export default {
// Create the object if not exists.
if (this.objectType === "x-dockge") {
if (!this.$parent.$parent.jsonConfig["x-dockge"]) {
this.$parent.$parent.jsonConfig["x-dockge"] = {};
if (!this.composePage.jsonConfig["x-dockge"]) {
this.composePage.jsonConfig["x-dockge"] = {};
}
}
@ -121,29 +122,3 @@ export default {
}
};
</script>
<style lang="scss" scoped>
@import "../styles/vars.scss";
.list-group {
background-color: $dark-bg2;
li {
display: flex;
align-items: center;
padding: 10px 0 10px 10px;
.domain-input {
flex-grow: 1;
background-color: $dark-bg2;
border: none;
color: $dark-font-color;
outline: none;
&::placeholder {
color: #1d2634;
}
}
}
}
</style>

View File

@ -1,27 +1,27 @@
<template>
<div>
<div v-if="valid">
<ul v-if="isArrayInited" class="list-group">
<li v-for="(value, index) in array" :key="index" class="list-group-item">
<select v-model="array[index]" class="no-bg domain-input">
<option value="">{{ $t(`Select a network...`) }}</option>
<option v-for="option in options" :key="option" :value="option">{{ option }}</option>
</select>
<font-awesome-icon icon="times" class="action remove ms-2 me-3 text-danger" @click="remove(index)" />
</li>
</ul>
<button class="btn btn-normal btn-sm mt-3" @click="addField">{{ $t("addListItem", [ displayName ]) }}</button>
</div>
<div v-else>
Long syntax is not supported here. Please use the YAML editor.
</div>
<div v-if="valid" class="grid gap-2">
<ul v-if="isArrayInited" class="grid gap-1.5">
<li v-for="(_, index) in array" :key="index" class="flex items-center gap-1.5">
<UiNativeSelect v-model="array[index]" :aria-label="displayName" class="min-w-0 flex-1">
<option value="">{{ $t("Select a network...") }}</option>
<option v-for="option in options" :key="option" :value="option">{{ option }}</option>
</UiNativeSelect>
<UiButton type="button" variant="ghost" size="icon" class="text-destructive" :aria-label="$t('removeEntry')" @click="remove(index)">
<AppIcon name="x" />
</UiButton>
</li>
</ul>
<UiButton type="button" variant="outline" size="sm" class="justify-self-start" @click="addField">
<AppIcon name="plus" /> {{ $t("addListItem", [ displayName ]) }}
</UiButton>
</div>
<p v-else class="text-sm text-muted-foreground">{{ $t("LongSyntaxNotSupported") }}</p>
</template>
<script>
export default {
inject: { containerEditor: { default: null },
composePage: {} },
props: {
name: {
type: String,
@ -64,7 +64,7 @@ export default {
},
service() {
return this.$parent.$parent.service;
return this.containerEditor.service;
},
valid() {
@ -100,29 +100,3 @@ export default {
}
};
</script>
<style lang="scss" scoped>
@import "../styles/vars.scss";
.list-group {
background-color: $dark-bg2;
li {
display: flex;
align-items: center;
padding: 10px 0 10px 10px;
.domain-input {
flex-grow: 1;
background-color: $dark-bg2;
border: none;
color: $dark-font-color;
outline: none;
&::placeholder {
color: #1d2634;
}
}
}
}
</style>

View File

@ -0,0 +1,27 @@
<template>
<div class="grid min-h-dvh place-items-center px-4 py-10">
<div class="grid w-full max-w-sm gap-5">
<div class="flex items-center justify-center gap-2 font-heading text-lg font-semibold">
<PhStack class="size-5" weight="duotone" />
Dockge
</div>
<UiCard>
<CardHeader>
<CardTitle class="font-heading text-xl"><h1>{{ title }}</h1></CardTitle>
</CardHeader>
<CardContent>
<slot />
</CardContent>
</UiCard>
<ForkCredit class="text-center" />
</div>
</div>
</template>
<script setup>
import { PhStack } from "@phosphor-icons/vue";
import ForkCredit from "./ForkCredit.vue";
defineProps({ title: { type: String,
required: true } });
</script>

View File

@ -1,84 +1,39 @@
<template>
<div ref="modal" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 id="exampleModalLabel" class="modal-title">
{{ title || $t("Confirm") }}
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" />
</div>
<div class="modal-body">
<slot />
</div>
<div class="modal-footer">
<button type="button" class="btn" :class="btnStyle" data-bs-dismiss="modal" @click="yes">
{{ yesText }}
</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" @click="no">
{{ noText }}
</button>
</div>
<AlertDialog v-model:open="open">
<AlertDialogContent :aria-describedby="undefined">
<AlertDialogHeader>
<AlertDialogTitle>{{ title || $t("Confirm") }}</AlertDialogTitle>
</AlertDialogHeader>
<div class="space-y-3 text-sm text-muted-foreground">
<slot />
</div>
</div>
</div>
<AlertDialogFooter>
<AlertDialogCancel @click="$emit('no')">{{ noText || $t("cancel") }}</AlertDialogCancel>
<AlertDialogAction :variant="destructive ? 'destructive' : 'default'" @click="$emit('yes')">
{{ yesText || $t("Yes") }}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</template>
<script>
import { Modal } from "bootstrap";
export default {
props: {
/** Style of button */
btnStyle: {
type: String,
default: "btn-primary",
},
/** Text to use as yes */
yesText: {
type: String,
default: "Yes", // TODO: No idea what to translate this
},
/** Text to use as no */
noText: {
type: String,
default: "No",
},
/** Title to show on modal. Defaults to translated version of "Config" */
title: {
type: String,
default: null,
}
destructive: Boolean,
yesText: { type: String,
default: "" },
noText: { type: String,
default: "" },
title: { type: String,
default: "" },
},
emits: [ "yes", "no" ],
data: () => ({
modal: null,
}),
mounted() {
this.modal = new Modal(this.$refs.modal);
},
data: () => ({ open: false }),
methods: {
/**
* Show the confirm dialog
* @returns {void}
*/
show() {
this.modal.show();
this.open = true;
},
/**
* @fires string "yes" Notify the parent when Yes is pressed
* @returns {void}
*/
yes() {
this.$emit("yes");
},
/**
* @fires string "no" Notify the parent when No is pressed
* @returns {void}
*/
no() {
this.$emit("no");
}
},
};
</script>

View File

@ -1,204 +1,107 @@
<template>
<div class="shadow-box big-padding mb-3 container">
<div class="row">
<div class="col-5">
<h4>{{ name }}</h4>
<div class="image mb-2">
<span class="me-1">{{ imageName }}:</span><span class="tag">{{ imageTag }}</span>
<UiCard class="gap-0 py-0">
<CardContent class="grid gap-3 p-3">
<div class="flex flex-wrap items-start justify-between gap-2">
<div class="min-w-0 flex-1">
<h3 class="break-all font-heading text-sm font-semibold">{{ name }}</h3>
<p v-if="envsubstService.image" class="mt-0.5 break-all font-mono text-xs text-muted-foreground">{{ envsubstService.image }}</p>
</div>
<div v-if="!isEditMode">
<span class="badge me-1" :class="bgStyle">{{ status }}</span>
<a v-for="port in (ports ?? envsubstService.ports)" :key="port" :href="parsePort(port).url" target="_blank">
<span class="badge me-1 bg-secondary">{{ parsePort(port).display }}</span>
</a>
</div>
</div>
<div class="col-7">
<div class="function">
<div class="btn-group me-2" role="group">
<router-link v-if="!isEditMode && (status === 'running' || status === 'healthy')" class="btn btn-normal" :to="terminalRouteLink" disabled="">
<font-awesome-icon icon="terminal" />
Bash
</router-link>
<button
v-if="serviceCount > 1 && !isEditMode && status !== 'running' && status !== 'healthy'"
class="btn btn-primary"
:disabled="processing"
@click="startService"
>
<font-awesome-icon icon="play" class="me-1" />
{{ $t("startStack") }}
</button>
<button
v-if="serviceCount > 1 && !isEditMode && (status === 'running' || status === 'healthy' || status === 'unhealthy')"
class="btn btn-normal"
:disabled="processing"
@click="restartService"
>
<font-awesome-icon icon="rotate" class="me-1" />
{{ $t("restartStack") }}
</button>
<button
v-if="serviceCount > 1 && !isEditMode && (status === 'running' || status === 'healthy' || status === 'unhealthy')"
class="btn btn-normal"
:disabled="processing"
@click="stopService"
>
<font-awesome-icon icon="stop" class="me-1" />
{{ $t("stopStack") }}
</button>
</div>
</div>
</div>
</div>
<div v-if="isEditMode" class="mt-2">
<button class="btn btn-normal me-2" @click="showConfig = !showConfig">
<font-awesome-icon icon="edit" />
{{ $t("Edit") }}
</button>
<button v-if="false" class="btn btn-normal me-2">Rename</button>
<button class="btn btn-danger me-2" @click="remove">
<font-awesome-icon icon="trash" />
{{ $t("deleteContainer") }}
</button>
</div>
<div v-else-if="statsInstances.length > 0" class="mt-2">
<div class="d-flex align-items-center gap-3">
<template v-if="!expandedStats">
<div class="stats">
{{ $t('CPU') }}: {{ statsInstances[0].CPUPerc }}
</div>
<div class="stats">
{{ $t('memoryAbbreviated') }}: {{ statsInstances[0].MemUsage }}
</div>
<template v-if="isEditMode">
<UiButton variant="outline" size="sm" :aria-expanded="showConfig" @click="showConfig = !showConfig">
<AppIcon name="edit" /> {{ $t("Edit") }}
</UiButton>
<UiButton variant="ghost" size="icon-sm" class="text-destructive" :aria-label="$t('deleteContainer')" @click="remove">
<AppIcon name="trash" />
</UiButton>
</template>
<template v-else>
<UiBadge variant="outline" class="status-badge" :data-status="status">{{ $t("resourceContainerState." + status, status) }}</UiBadge>
<UiButton v-if="fileTargets.length === 1" as-child variant="outline" size="sm">
<router-link :to="fileRoute(fileTargets[0])"><AppIcon name="folder" /> {{ $t("containerFiles") }}</router-link>
</UiButton>
<DropdownMenu v-if="shellAvailable || serviceCount > 1 || fileTargets.length > 1">
<DropdownMenuTrigger as-child>
<UiButton variant="ghost" size="icon-sm" :disabled="composePage.processing" :aria-label="$t('moreActions')"><AppIcon name="dots" /></UiButton>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<template v-if="fileTargets.length > 1">
<DropdownMenuItem v-for="instance in fileTargets" :key="instance.id" as-child>
<router-link :to="fileRoute(instance)"><AppIcon name="folder" /> {{ $t("containerFileInstance", { name: instance.name }) }}</router-link>
</DropdownMenuItem>
<DropdownMenuSeparator />
</template>
<DropdownMenuItem v-if="shellAvailable" as-child>
<router-link :to="terminalRouteLink"><AppIcon name="terminal" /> Bash</router-link>
</DropdownMenuItem>
<template v-if="serviceCount > 1">
<DropdownMenuItem v-if="!shellAvailable" @select="startService"><AppIcon name="play" /> {{ $t("startStack") }}</DropdownMenuItem>
<DropdownMenuItem v-if="shellAvailable || status === 'unhealthy'" @select="restartService"><AppIcon name="restart" /> {{ $t("restartStack") }}</DropdownMenuItem>
<DropdownMenuItem v-if="shellAvailable || status === 'unhealthy'" @select="stopService"><AppIcon name="stop" /> {{ $t("stopStack") }}</DropdownMenuItem>
</template>
</DropdownMenuContent>
</DropdownMenu>
</template>
<div class="d-flex flex-grow-1 justify-content-end">
<button class="btn btn-sm btn-normal" @click="expandedStats = !expandedStats">
<font-awesome-icon :icon="expandedStats ? 'chevron-up' : 'chevron-down'" />
</button>
</div>
</div>
<transition name="slide-fade" appear>
<div v-if="expandedStats" class="d-flex flex-column gap-3 mt-2">
<DockerStat
v-for="stat in statsInstances"
:key="stat.Name"
:stat="stat"
/>
<div v-if="!isEditMode && envsubstService.ports?.length" class="flex flex-wrap gap-1.5">
<UiBadge v-for="port in envsubstService.ports" :key="port" as-child variant="secondary">
<a :href="parsePort(port).url" target="_blank" rel="noopener noreferrer">{{ parsePort(port).display }}</a>
</UiBadge>
</div>
<Collapsible v-if="!isEditMode && statsInstances.length" class="border-t pt-2">
<CollapsibleTrigger as-child>
<UiButton variant="ghost" size="sm" class="group max-w-full justify-start text-muted-foreground">
<AppIcon name="caret-down" class="group-data-[state=closed]:-rotate-90" />
<span>{{ $t("stackResourceStats") }}</span>
</UiButton>
</CollapsibleTrigger>
<CollapsibleContent class="mt-2 grid gap-2">
<DockerStat v-for="stat in statsInstances" :key="stat.Name" :stat="stat" />
</CollapsibleContent>
</Collapsible>
<div v-if="isEditMode && showConfig" class="grid gap-4 border-t pt-3">
<div class="grid gap-1.5">
<UiLabel :for="name + '-image'">{{ $t("dockerImage") }}</UiLabel>
<UiInput :id="name + '-image'" v-model="service.image" />
</div>
</transition>
</div>
<transition name="slide-fade" appear>
<div v-if="isEditMode && showConfig" class="config mt-3">
<!-- Image -->
<div class="mb-4">
<label class="form-label">
{{ $t("dockerImage") }}
</label>
<div class="input-group mb-3">
<input
v-model="service.image"
class="form-control"
list="image-datalist"
/>
</div>
<!-- TODO: Search online: https://hub.docker.com/api/content/v1/products/search?q=louislam%2Fuptime&source=community&page=1&page_size=4 -->
<datalist id="image-datalist">
<option value="louislam/uptime-kuma:1" />
</datalist>
<div class="form-text"></div>
</div>
<!-- Ports -->
<div class="mb-4">
<label class="form-label">
{{ $tc("port", 2) }}
</label>
<ArrayInput name="ports" :display-name="$t('port')" placeholder="HOST:CONTAINER" />
</div>
<!-- Volumes -->
<div class="mb-4">
<label class="form-label">
{{ $tc("volume", 2) }}
</label>
<ArrayInput name="volumes" :display-name="$t('volume')" placeholder="HOST:CONTAINER" />
</div>
<!-- Restart Policy -->
<div class="mb-4">
<label class="form-label">
{{ $t("restartPolicy") }}
</label>
<select v-model="service.restart" class="form-select">
<div class="grid gap-1.5">
<UiLabel :for="name + '-restart'">{{ $t("restartPolicy") }}</UiLabel>
<UiNativeSelect :id="name + '-restart'" :model-value="service.restart || 'no'" class="w-full" @update:model-value="service.restart = $event">
<option value="always">{{ $t("restartPolicyAlways") }}</option>
<option value="unless-stopped">{{ $t("restartPolicyUnlessStopped") }}</option>
<option value="on-failure">{{ $t("restartPolicyOnFailure") }}</option>
<option value="no">{{ $t("restartPolicyNo") }}</option>
</select>
</UiNativeSelect>
</div>
<!-- Environment Variables -->
<div class="mb-4">
<label class="form-label">
{{ $tc("environmentVariable", 2) }}
</label>
<ArrayInput name="environment" :display-name="$t('environmentVariable')" placeholder="KEY=VALUE" />
<div v-for="field in listFields" :key="field.name" class="grid gap-1.5">
<p class="text-sm font-medium">{{ field.plural ? $tc(field.label, 2) : $t(field.label) }}</p>
<ArrayInput :name="field.name" :display-name="$t(field.label)" :placeholder="field.placeholder || $t('containerName')" />
</div>
<!-- Container Name -->
<div v-if="false" class="mb-4">
<label class="form-label">
{{ $t("containerName") }}
</label>
<div class="input-group mb-3">
<input
v-model="service.container_name"
class="form-control"
/>
</div>
<div class="form-text"></div>
</div>
<!-- Network -->
<div class="mb-4">
<label class="form-label">
{{ $tc("network", 2) }}
</label>
<div v-if="networkList.length === 0 && service.networks && service.networks.length > 0" class="text-warning mb-3">
{{ $t("NoNetworksAvailable") }}
</div>
<ArraySelect name="networks" :display-name="$t('network')" placeholder="Network Name" :options="networkList" />
</div>
<!-- Depends on -->
<div class="mb-4">
<label class="form-label">
{{ $t("dependsOn") }}
</label>
<ArrayInput name="depends_on" :display-name="$t('dependsOn')" :placeholder="$t(`containerName`)" />
<div class="grid gap-1.5">
<p class="text-sm font-medium">{{ $tc("network", 2) }}</p>
<UiAlert v-if="!networkList.length && service.networks?.length">{{ $t("NoNetworksAvailable") }}</UiAlert>
<ArraySelect name="networks" :display-name="$t('network')" :options="networkList" />
</div>
</div>
</transition>
</div>
</CardContent>
</UiCard>
</template>
<script>
import { defineComponent } from "vue";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import { parseDockerPort } from "../../../common/util-common";
import ArrayInput from "./ArrayInput.vue";
import ArraySelect from "./ArraySelect.vue";
import DockerStat from "./DockerStat.vue";
export default defineComponent({
components: {
FontAwesomeIcon,
DockerStat
components: { ArrayInput,
ArraySelect,
DockerStat },
inject: [ "composePage" ],
provide() {
return { containerEditor: this };
},
props: {
name: {
@ -209,10 +112,6 @@ export default defineComponent({
type: Boolean,
default: false,
},
first: {
type: Boolean,
default: false,
},
serviceStatus: {
type: Object,
default: null,
@ -230,7 +129,22 @@ export default defineComponent({
data() {
return {
showConfig: false,
expandedStats: false,
listFields: [
{ name: "ports",
label: "port",
placeholder: "HOST:CONTAINER",
plural: true },
{ name: "volumes",
label: "volume",
placeholder: "HOST:CONTAINER",
plural: true },
{ name: "environment",
label: "environmentVariable",
placeholder: "KEY=VALUE",
plural: true },
{ name: "depends_on",
label: "dependsOn" },
],
};
},
computed: {
@ -243,16 +157,12 @@ export default defineComponent({
return list;
},
bgStyle() {
if (this.status === "running" || this.status === "healthy") {
return "bg-primary";
} else if (this.status === "unhealthy") {
return "bg-danger";
} else {
return "bg-secondary";
}
fileTargets() {
return (this.serviceStatus || []).filter(instance => instance.state === "running" && /^[0-9a-f]{64}$/.test(instance.id || ""));
},
shellAvailable() {
return this.status === "running" || this.status === "healthy";
},
terminalRouteLink() {
if (this.endpoint) {
return {
@ -277,15 +187,15 @@ export default defineComponent({
},
endpoint() {
return this.$parent.$parent.endpoint;
return this.composePage.endpoint;
},
stack() {
return this.$parent.$parent.stack;
return this.composePage.stack;
},
stackName() {
return this.$parent.$parent.stack.name;
return this.composePage.stack.name;
},
service() {
@ -300,40 +210,15 @@ export default defineComponent({
},
jsonObject() {
return this.$parent.$parent.jsonConfig;
return this.composePage.jsonConfig;
},
envsubstJSONConfig() {
return this.$parent.$parent.envsubstJSONConfig;
return this.composePage.envsubstJSONConfig;
},
envsubstService() {
if (!this.envsubstJSONConfig.services[this.name]) {
return {};
}
return this.envsubstJSONConfig.services[this.name];
},
imageName() {
if (this.envsubstService.image) {
return this.envsubstService.image.split(":")[0];
} else {
return "";
}
},
imageTag() {
if (this.envsubstService.image) {
let tag = this.envsubstService.image.split(":")[1];
if (tag) {
return tag;
} else {
return "latest";
}
} else {
return "";
}
return this.envsubstJSONConfig.services?.[this.name] ?? {};
},
statsInstances() {
if (!this.serviceStatus) {
@ -341,23 +226,20 @@ export default defineComponent({
}
return this.serviceStatus
.map(s => this.dockerStats[s.name])
.map(s => this.dockerStats?.[s.name])
.filter(s => !!s)
.sort((a, b) => a.Name.localeCompare(b.Name));
},
status() {
if (!this.serviceStatus) {
return "N/A";
}
return this.serviceStatus[0].status;
}
},
mounted() {
if (this.first) {
//this.showConfig = true;
return this.serviceStatus?.[0]?.status ?? "N/A";
}
},
methods: {
fileRoute(instance) {
return { name: "containerFiles",
params: { id: instance.id,
endpoint: this.endpoint } };
},
parsePort(port) {
if (this.stack.endpoint) {
return parseDockerPort(port, this.stack.primaryHostname);
@ -382,31 +264,3 @@ export default defineComponent({
}
});
</script>
<style scoped lang="scss">
@import "../styles/vars";
.container {
.image {
font-size: 0.8rem;
color: #6c757d;
.tag {
color: #33383b;
}
}
.function {
align-content: center;
display: flex;
height: 100%;
width: 100%;
align-items: center;
justify-content: end;
}
.stats {
font-size: 0.8rem;
color: #6c757d;
}
}
</style>

View File

@ -1,42 +1,12 @@
<template>
<div class="stats-container">
<div class="stats-title">
{{ stat.Name }}
</div>
<div class="d-flex justify-content-between stats gap-2 mt-1">
<div class="stat">
<div class="stat-label">
{{ $t('CPU') }}
</div>
<div>
{{ stat.CPUPerc }}
</div>
<div class="rounded-lg border bg-muted/25 p-3 text-xs">
<p class="mb-2 truncate font-mono text-muted-foreground">{{ stat.Name }}</p>
<dl class="grid grid-cols-2 gap-2">
<div v-for="item in metrics" :key="item.label" class="min-w-0">
<dt class="text-muted-foreground">{{ $t(item.label) }}</dt>
<dd class="break-words font-medium tabular-nums">{{ item.value }}</dd>
</div>
<div class="stat">
<div class="stat-label">
{{ $t('memory') }}
</div>
<div>
{{ stat.MemUsage }} ({{ stat.MemPerc }})
</div>
</div>
<div class="stat">
<div class="stat-label">
{{ $t('networkIO') }}
</div>
<div>
{{ stat.NetIO }}
</div>
</div>
<div class="stat">
<div class="stat-label">
{{ $t('blockIO') }}
</div>
<div>
{{ stat.BlockIO }}
</div>
</div>
</div>
</dl>
</div>
</template>
@ -48,47 +18,19 @@ export default {
required: true
}
},
computed: {
metrics() {
return [
{ label: "CPU",
value: this.stat.CPUPerc },
{ label: "memory",
value: this.stat.MemUsage + " (" + this.stat.MemPerc + ")" },
{ label: "networkIO",
value: this.stat.NetIO },
{ label: "blockIO",
value: this.stat.BlockIO },
];
},
},
};
</script>
<style lang="scss" scoped>
.stats-container {
container-type: inline-size;
.stats {
container-type: inline-size;
.stat {
display: flex;
flex-direction: column;
gap: 4px;
}
@container (width < 420px) {
flex-direction: column;
.stat {
flex-direction: row;
}
.stat-label::after {
content: ':'
}
}
}
}
.stats {
font-size: 0.8rem;
color: #6c757d;
}
.stat-label {
font-weight: bold;
}
.stats-title {
font-size: 0.9rem;
color: var(--bs-heading-color);
}
</style>

View File

@ -0,0 +1,3 @@
<template>
<p class="text-sm text-muted-foreground">{{ $t("forkCredit") }}</p>
</template>

View File

@ -1,23 +1,9 @@
<template>
<div class="input-group mb-3">
<input
ref="input"
v-model="model"
:type="visibility"
class="form-control"
:placeholder="placeholder"
:maxlength="maxlength"
:autocomplete="autocomplete"
:required="required"
:readonly="readonly"
>
<a v-if="visibility == 'password'" class="btn btn-outline-primary" @click="showInput()">
<font-awesome-icon icon="eye" />
</a>
<a v-if="visibility == 'text'" class="btn btn-outline-primary" @click="hideInput()">
<font-awesome-icon icon="eye-slash" />
</a>
<div class="flex gap-1.5">
<UiInput v-model="model" :type="visibility" :placeholder="placeholder" :maxlength="maxlength" :autocomplete="autocomplete" :required="required" :readonly="readonly" />
<UiButton type="button" variant="outline" size="icon" :aria-label="$t('Password')" :aria-pressed="visibility === 'text'" @click="visibility = visibility === 'password' ? 'text' : 'password'">
<AppIcon :name="visibility === 'password' ? 'eye' : 'eye-off'" />
</UiButton>
</div>
</template>
@ -70,18 +56,5 @@ export default {
}
}
},
created() {
},
methods: {
/** Show users input in plain text */
showInput() {
this.visibility = "text";
},
/** Censor users input */
hideInput() {
this.visibility = "password";
},
}
};
</script>

View File

@ -1,102 +1,97 @@
<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">
<section class="grid min-w-0 gap-3">
<div class="flex flex-wrap items-start justify-between gap-3">
<p class="max-w-prose text-sm text-muted-foreground">{{ $t("imageScanDescription") }}</p>
<div class="flex flex-wrap gap-2">
<UiButton type="button" variant="outline" :disabled="requestPending" @click="refreshReport">
{{ $t("imageScanRefresh") }}
</button>
<button type="button" class="btn btn-primary" :disabled="requestPending || running" @click="startScan">
</UiButton>
<UiButton type="button" :disabled="requestPending || running" @click="startScan">
{{ $t("imageScanStart") }}
</button>
</UiButton>
</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 }) }}
<UiAlert v-if="error" variant="destructive">{{ $t(error) }}</UiAlert>
<p v-if="running" class="text-sm text-muted-foreground" role="status">
{{ report.preparingDatabase ? $t("imageScanPreparingDatabase") : $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>
<UiAlert v-else-if="report?.status === 'failed'">{{ $t(report.error) }}</UiAlert>
<p v-else-if="report && report.images.length === 0" class="text-sm text-muted-foreground">{{ $t("imageScanNoImages") }}</p>
<p v-else-if="!report && !requestPending" class="text-sm text-muted-foreground">{{ $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">
<div class="grid gap-2 md:grid-cols-[minmax(0,1fr)_11rem]">
<label class="grid min-w-0 gap-1.5 text-sm font-medium">
<span>{{ $t("imageScanImage") }}</span>
<select v-model="selectedImage" class="form-select" :aria-label="$t('imageScanImage')" @change="loadFindings(0)">
<UiNativeSelect v-model="selectedImage" class="w-full min-w-0" :aria-label="$t('imageScanImage')" @update:model-value="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>
</UiNativeSelect>
</label>
<label v-if="selected?.status === 'scanned'" class="image-security-field">
<label v-if="selected?.status === 'scanned'" class="grid min-w-0 gap-1.5 text-sm font-medium">
<span>{{ $t("imageScanSeverityLabel") }}</span>
<select v-model="severity" class="form-select" :aria-label="$t('imageScanSeverityLabel')" @change="loadFindings(0)">
<UiNativeSelect v-model="severity" class="w-full min-w-0" :aria-label="$t('imageScanSeverityLabel')" @update:model-value="loadFindings(0)">
<option value="">{{ $t("imageScanAllSeverities") }}</option>
<option v-for="level in severities" :key="level" :value="level">{{ $t("imageScanSeverity." + level) }}</option>
</select>
</UiNativeSelect>
</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">
<p class="my-2 break-all font-mono text-xs text-muted-foreground">{{ selected.id }}</p>
<p v-if="selected.databaseBuiltAt" class="text-xs text-muted-foreground 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>
<UiAlert v-if="selected.error">{{ $t(selected.error) }}</UiAlert>
<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">
<div class="flex flex-wrap gap-1.5" role="group" :aria-label="$t('imageScanCounts')">
<UiBadge v-for="level in severities" :key="level" variant="outline" class="severity-badge" :data-severity="level">
{{ $t("imageScanSeverity." + level) }} {{ selected.counts[level] }}
</span>
</UiBadge>
</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>
<p v-if="selected.truncated" class="text-xs text-muted-foreground mt-2 mb-0">{{ $t("imageScanTruncated") }}</p>
<p v-if="findingsPending" class="text-sm text-muted-foreground" role="status">{{ $t("imageScanLoading") }}</p>
<p v-else-if="!rows.length && !error" class="text-sm text-muted-foreground">{{ $t("imageScanNoFindings") }}</p>
<div v-else-if="rows.length" class="mt-3 min-w-0 rounded-lg border">
<UiTable class="min-w-[38rem]">
<TableCaption class="sr-only">{{ $t("imageScanFindings") }}</TableCaption>
<TableHeader>
<TableRow>
<TableHead scope="col">{{ $t("imageScanSeverityLabel") }}</TableHead>
<TableHead scope="col">{{ $t("imageScanAdvisory") }}</TableHead>
<TableHead scope="col">{{ $t("imageScanPackage") }}</TableHead>
<TableHead scope="col">{{ $t("imageScanInstalled") }}</TableHead>
<TableHead scope="col">{{ $t("imageScanFixed") }}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="(finding, index) in rows" :key="index">
<TableCell><UiBadge variant="outline" class="severity-badge" :data-severity="finding.severity">{{ $t("imageScanSeverity." + finding.severity) }}</UiBadge></TableCell>
<TableCell>
<a v-if="advisoryURL(finding.id)" :href="advisoryURL(finding.id)" target="_blank" rel="noopener noreferrer" class="underline underline-offset-4">{{ 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>
</TableCell>
<TableCell>{{ finding.packageName }}<span class="block text-xs text-muted-foreground">{{ finding.packageType }} · {{ finding.namespace }}</span></TableCell>
<TableCell>{{ finding.installedVersion }}</TableCell>
<TableCell>{{ finding.fixedVersions.join(", ") || $t("imageScanFixUnknown") }}</TableCell>
</TableRow>
</TableBody>
</UiTable>
</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 v-if="total > pageSize" class="mt-2 flex flex-wrap items-center justify-between gap-2">
<UiButton type="button" variant="outline" :disabled="findingsPending || offset === 0" @click="loadFindings(offset - pageSize)">{{ $t("imageScanPrevious") }}</UiButton>
<span class="text-xs text-muted-foreground" role="status">{{ $t("imageScanPage", { first: offset + 1, last: Math.min(offset + pageSize, total), total }) }}</span>
<UiButton type="button" variant="outline" :disabled="findingsPending || offset + pageSize >= total" @click="loadFindings(offset + pageSize)">{{ $t("imageScanNext") }}</UiButton>
</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>
<p v-if="report?.finishedAt" class="text-xs text-muted-foreground mt-3 mb-0">{{ $t("imageScanTimestamp", { time: new Date(report.finishedAt).toLocaleString($i18n.locale) }) }}</p>
<p class="text-xs text-muted-foreground mt-2 mb-0">{{ $t("imageScanRetention") }}</p>
</section>
</template>
@ -271,100 +266,3 @@ export default {
},
};
</script>
<style scoped lang="scss">
.image-security {
min-width: 0;
}
.image-security-header,
.image-security-actions,
.image-security-counts,
.image-security-pagination {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.5rem;
}
.image-security-header {
justify-content: space-between;
gap: 1rem;
}
.image-security-filters {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(10rem, auto);
gap: 0.75rem;
}
.image-security-field {
display: grid;
gap: 0.25rem;
min-width: 0;
font-size: 0.875rem;
}
.image-security-id,
.image-security-table td {
overflow-wrap: anywhere;
}
.image-security-table {
min-width: 40rem;
font-size: 0.875rem;
}
.image-security-severity {
display: inline-flex;
align-items: center;
padding: 0.125rem 0.5rem;
border: 1px solid currentColor;
border-radius: 1rem;
color: #536270;
font-size: 0.75rem;
white-space: nowrap;
&[data-severity="critical"] {
color: #9d174d;
}
&[data-severity="high"] {
color: #ad2929;
}
&[data-severity="medium"] {
color: #8a490b;
}
&[data-severity="low"] {
color: #1d5a97;
}
}
.dark .image-security-severity {
color: #b1bdca;
&[data-severity="critical"] {
color: #ffa3ce;
}
&[data-severity="high"] {
color: #ffaaaa;
}
&[data-severity="medium"] {
color: #ffce8c;
}
&[data-severity="low"] {
color: #9ac8ff;
}
}
@media (max-width: 600px) {
.image-security-filters {
grid-template-columns: minmax(0, 1fr);
}
}
</style>

View File

@ -1,49 +1,35 @@
<template>
<div class="form-container">
<div class="form">
<form @submit.prevent="submit">
<h1 class="h3 mb-3 fw-normal" />
<div v-if="!tokenRequired" class="form-floating">
<input id="floatingInput" v-model="username" type="text" class="form-control" placeholder="Username" autocomplete="username" required>
<label for="floatingInput">{{ $t("Username") }}</label>
<AuthCard :title="$t('Login')">
<form class="grid gap-4" @submit.prevent="submit">
<template v-if="!tokenRequired">
<div class="grid gap-2">
<UiLabel for="login-name">{{ $t("Username") }}</UiLabel>
<UiInput id="login-name" v-model="username" autocomplete="username" required />
</div>
<div v-if="!tokenRequired" class="form-floating mt-3">
<input id="floatingPassword" v-model="password" type="password" class="form-control" placeholder="Password" autocomplete="current-password" required>
<label for="floatingPassword">{{ $t("Password") }}</label>
<div class="grid gap-2">
<UiLabel for="login-password">{{ $t("Password") }}</UiLabel>
<UiInput id="login-password" v-model="password" type="password" autocomplete="current-password" required />
</div>
<div v-if="tokenRequired">
<div class="form-floating mt-3">
<input id="otp" v-model="token" type="text" maxlength="6" class="form-control" placeholder="123456" autocomplete="one-time-code" required>
<label for="otp">{{ $t("Token") }}</label>
</div>
</div>
<div class="form-check mb-3 mt-3 d-flex justify-content-center pe-4">
<div class="form-check">
<input id="remember" v-model="$root.remember" type="checkbox" value="remember-me" class="form-check-input">
<label class="form-check-label" for="remember">
{{ $t("Remember me") }}
</label>
</div>
</div>
<button class="w-100 btn btn-primary" type="submit" :disabled="processing">
{{ $t("Login") }}
</button>
<div v-if="res && !res.ok" class="alert alert-danger mt-3" role="alert">
{{ $t(res.msg) }}
</div>
</form>
</div>
</div>
</template>
<div v-else class="grid gap-2">
<UiLabel for="otp">{{ $t("Token") }}</UiLabel>
<UiInput id="otp" v-model="token" inputmode="numeric" maxlength="6" placeholder="123456" autocomplete="one-time-code" required />
</div>
<div class="flex items-center gap-2">
<UiCheckbox id="remember" v-model="$root.remember" />
<UiLabel for="remember">{{ $t("Remember me") }}</UiLabel>
</div>
<UiButton type="submit" class="w-full" :disabled="processing">{{ $t("Login") }}</UiButton>
<UiAlert v-if="res && !res.ok" variant="destructive">{{ $t(res.msg) }}</UiAlert>
</form>
</AuthCard>
</template>
<script>
import AuthCard from "./AuthCard.vue";
export default {
components: { AuthCard },
data() {
return {
processing: false,
@ -85,30 +71,3 @@ export default {
},
};
</script>
<style lang="scss" scoped>
.form-container {
display: flex;
align-items: center;
padding-top: 40px;
padding-bottom: 40px;
}
.form-floating {
> label {
padding-left: 1.3rem;
}
> .form-control {
padding-left: 1.3rem;
}
}
.form {
width: 100%;
max-width: 330px;
padding: 15px;
margin: auto;
text-align: center;
}
</style>

View File

@ -1,50 +1,29 @@
<template>
<div>
<h5>{{ $t("Internal Networks") }}</h5>
<ul class="list-group">
<li v-for="(networkRow, index) in networkList" :key="index" class="list-group-item">
<input v-model="networkRow.key" type="text" class="no-bg domain-input" :placeholder="$t(`Network name...`)" />
<font-awesome-icon icon="times" class="action remove ms-2 me-3 text-danger" @click="remove(index)" />
</li>
</ul>
<button class="btn btn-normal btn-sm mt-3 me-2" @click="addField">{{ $t("addInternalNetwork") }}</button>
<h5 class="mt-3">{{ $t("External Networks") }}</h5>
<div v-if="externalNetworkList.length === 0">
{{ $t("No External Networks") }}
</div>
<div v-for="(networkName, index) in externalNetworkList" :key="networkName" class="form-check form-switch my-3">
<input :id=" 'external-network' + index" v-model="selectedExternalList[networkName]" class="form-check-input" type="checkbox">
<label class="form-check-label" :for=" 'external-network' +index">
{{ networkName }}
</label>
<span v-if="false" class="text-danger ms-2 delete">Delete</span>
</div>
<div v-if="false" class="input-group mb-3">
<input
placeholder="New external network name..."
class="form-control"
@keyup.enter="createExternelNetwork"
/>
<button class="btn btn-normal btn-sm me-2" type="button">
{{ $t("createExternalNetwork") }}
</button>
</div>
<div v-if="false">
<button class="btn btn-primary btn-sm mt-3 me-2" @click="applyToYAML">{{ $t("applyToYAML") }}</button>
</div>
<div class="grid gap-4">
<section class="grid gap-2">
<h3 class="text-sm font-medium">{{ $t("Internal Networks") }}</h3>
<ul class="grid gap-1.5">
<li v-for="(networkRow, index) in networkList" :key="index" class="flex gap-1.5">
<UiInput v-model="networkRow.key" :aria-label="$t('Network name...')" :placeholder="$t('Network name...')" />
<UiButton type="button" variant="ghost" size="icon" class="text-destructive" :aria-label="$t('removeEntry')" @click="remove(index)"><AppIcon name="x" /></UiButton>
</li>
</ul>
<UiButton type="button" variant="outline" size="sm" class="justify-self-start" @click="addField"><AppIcon name="plus" /> {{ $t("addInternalNetwork") }}</UiButton>
</section>
<section class="grid gap-2 border-t pt-3">
<h3 class="text-sm font-medium">{{ $t("External Networks") }}</h3>
<p v-if="!externalNetworkList.length" class="text-sm text-muted-foreground">{{ $t("No External Networks") }}</p>
<div v-for="(networkName, index) in externalNetworkList" :key="networkName" class="flex items-center gap-2">
<UiSwitch :id="'external-network-' + index" v-model="selectedExternalList[networkName]" />
<UiLabel :for="'external-network-' + index">{{ networkName }}</UiLabel>
</div>
</section>
</div>
</template>
<script>
export default {
inject: [ "composePage" ],
data() {
return {
networkList: [],
@ -57,15 +36,15 @@ export default {
},
computed: {
jsonConfig() {
return this.$parent.$parent.jsonConfig;
return this.composePage.jsonConfig;
},
stack() {
return this.$parent.$parent.stack;
return this.composePage.stack;
},
endpoint() {
return this.$parent.$parent.endpoint;
return this.composePage.endpoint;
},
},
watch: {
@ -201,35 +180,3 @@ export default {
},
};
</script>
<style lang="scss" scoped>
@import "../styles/vars.scss";
.list-group {
background-color: $dark-bg2;
li {
display: flex;
align-items: center;
padding: 10px 0 10px 10px;
.domain-input {
flex-grow: 1;
background-color: $dark-bg2;
border: none;
color: $dark-font-color;
outline: none;
&::placeholder {
color: #1d2634;
}
}
}
}
.delete {
text-decoration: underline;
font-size: 13px;
cursor: pointer;
}
</style>

View File

@ -1,26 +1,26 @@
<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">
<Tabs v-model="activeFile" class="config-tabs gap-0" :unmount-on-hide="false">
<div class="flex flex-wrap items-center justify-between gap-2 border-b p-2">
<TabsList variant="line" class="max-w-full overflow-x-auto" :aria-label="$t('editorFiles')">
<TabsTrigger value="yaml">
{{ fileName }}
<span v-if="yamlErrorCount" class="config-error-count">{{ yamlErrorCount }}</span>
</TabTrigger>
<TabTrigger value="env" class="config-tab">
<span v-if="yamlErrorCount" class="text-destructive">{{ yamlErrorCount }}</span>
</TabsTrigger>
<TabsTrigger value="env">
.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>
<span v-if="envErrorCount" class="text-destructive">{{ envErrorCount }}</span>
</TabsTrigger>
</TabsList>
<div class="flex flex-wrap items-center gap-0.5">
<UiButton type="button" variant="ghost" size="sm" @click="find">{{ $t("editorFind") }}</UiButton>
<UiButton v-if="editable && activeFile === 'yaml'" type="button" variant="ghost" size="sm" :disabled="disabled || yamlErrorCount > 0" @click="formatYAML">{{ $t("editorFormat") }}</UiButton>
<UiButton type="button" variant="ghost" size="sm" :aria-pressed="wrap" @click="wrap = !wrap">{{ $t("editorWrap") }}</UiButton>
<UiButton v-if="fullscreenAvailable" type="button" variant="ghost" size="sm" :aria-pressed="fullscreen" @click="toggleFullscreen">{{ $t(fullscreen ? "editorExitFullscreen" : "editorFullscreen") }}</UiButton>
</div>
</div>
<TabContent value="yaml" class="config-tab-content">
<TabsContent value="yaml" class="config-tab-content">
<CodeMirror
ref="yamlEditor" v-model="yamlModel" basic
:readonly="!editable || disabled" :wrap="wrap" :dark="$root.isDark"
@ -28,8 +28,8 @@
:linter-config="{ delay: 200 }" gutter indent-unit=" "
@ready="labelEditor('yaml')" @update="updateCursor($event, 'yaml')"
/>
</TabContent>
<TabContent value="env" class="config-tab-content">
</TabsContent>
<TabsContent value="env" class="config-tab-content">
<CodeMirror
ref="envEditor" v-model="envModel" basic
:readonly="!editable || disabled" :wrap="wrap" :dark="$root.isDark"
@ -37,32 +37,31 @@
:linter-config="{ delay: 200 }" gutter
@ready="labelEditor('env')" @update="updateCursor($event, 'env')"
/>
</TabContent>
</TabsRoot>
</TabsContent>
</Tabs>
<div class="config-status" role="status">
<div class="flex flex-wrap justify-between gap-2 border-t px-3 py-2 text-xs text-muted-foreground" 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')">
<ul v-if="diagnostics.length" class="max-h-40 overflow-auto border-t p-2 text-sm" :aria-label="$t('editorDiagnostics')">
<li v-for="(issue, index) in diagnostics" :key="index" :class="'config-' + issue.severity">
<button type="button" @click="jumpTo(issue)">
<UiButton type="button" variant="ghost" class="h-auto max-w-full justify-start whitespace-normal text-start" @click="jumpTo(issue)">
{{ issue.file === "yaml" ? fileName : ".env" }} · {{ $t("editorLine", { line: issue.line }) }} · {{ issue.message }}
</button>
</UiButton>
</li>
</ul>
</section>
</template>
<script>
import { TabContent, TabList, TabsRoot, TabTrigger } from "@ark-ui/vue/tabs";
import CodeMirror from "vue-codemirror6";
import { editorTheme } from "../lib/editor-theme";
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";
@ -122,10 +121,6 @@ const envLanguage = StreamLanguage.define({
export default {
components: {
TabsRoot,
TabList,
TabTrigger,
TabContent,
CodeMirror,
},
props: {
@ -185,10 +180,10 @@ export default {
},
},
yamlExtensions() {
return [ yamlLanguage(), ...(this.$root.isDark ? [ dracula ] : []) ];
return [ yamlLanguage(), ...editorTheme ];
},
envExtensions() {
return [ envLanguage, ...(this.$root.isDark ? [ dracula ] : []) ];
return [ envLanguage, ...editorTheme ];
},
saveKeymap() {
return [
@ -354,142 +349,3 @@ export default {
},
};
</script>
<style scoped lang="scss">
.stack-config-editor {
overflow: hidden;
border: 1px solid var(--stack-nav-colors-border);
border-radius: 0.875rem;
background: var(--stack-nav-colors-surface);
color: var(--stack-nav-colors-text);
}
.config-toolbar,
.config-tools,
.config-tab-list,
.config-status {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.375rem;
}
.config-toolbar {
justify-content: space-between;
padding: 0.5rem;
border-bottom: 1px solid var(--stack-nav-colors-border);
}
.config-tab,
.config-tool {
min-height: 2.25rem;
border: 1px solid transparent;
border-radius: 0.375rem;
padding: 0.25rem 0.5rem;
color: inherit;
background: transparent;
font-size: 0.8125rem;
}
.config-tab[data-selected] {
background: var(--stack-nav-colors-accent-subtle);
color: var(--stack-nav-colors-accent);
font-weight: 600;
}
.config-tool:hover {
background: var(--stack-nav-colors-subtle);
}
.config-tool:disabled {
opacity: 0.5;
}
.config-tab:focus-visible,
.config-tool:focus-visible,
.config-diagnostics button:focus-visible {
outline: 2px solid var(--stack-nav-colors-accent);
outline-offset: 1px;
}
.config-tab-content[hidden] {
display: none;
}
.config-tab-content :deep(.cm-editor) {
height: 28rem;
font-family: "JetBrains Mono", monospace;
font-size: 0.8125rem;
}
.config-tab-content :deep(.cm-scroller) {
overflow: auto;
}
.config-status {
justify-content: space-between;
padding: 0.5rem 0.75rem;
border-top: 1px solid var(--stack-nav-colors-border);
color: var(--stack-nav-colors-muted);
font-size: 0.75rem;
}
.config-diagnostics {
max-height: 10rem;
overflow: auto;
margin: 0;
padding: 0.5rem 0.75rem 0.5rem 1.75rem;
border-top: 1px solid var(--stack-nav-colors-border);
font-size: 0.8125rem;
button {
border: 0;
padding: 0.25rem;
color: inherit;
background: transparent;
text-align: start;
overflow-wrap: anywhere;
}
}
.config-error,
.config-error-count {
color: var(--stack-nav-colors-danger);
}
.stack-config-editor:fullscreen {
display: flex;
flex-direction: column;
padding: 1rem;
.config-tabs,
.config-tab-content,
.config-tab-content :deep(.vue-codemirror),
.config-tab-content :deep(.cm-editor) {
flex: 1;
min-height: 0;
}
.config-tabs,
.config-tab-content {
display: flex;
flex-direction: column;
}
.config-tab-content[hidden] {
display: none;
}
.config-tab-content :deep(.cm-editor) {
height: 100%;
}
}
@media (max-width: 600px) {
.config-toolbar {
align-items: stretch;
flex-direction: column;
}
}
</style>

View File

@ -1,92 +1,83 @@
<template>
<nav class="stack-nav-panel" :aria-label="$t('stackListTitle')">
<div class="stack-nav-header">
<nav class="grid min-w-0 grid-cols-[minmax(0,1fr)] gap-3 p-4" :aria-label="$t('stackListTitle')">
<div class="flex min-h-8 items-center justify-between gap-2 pe-10 md:pe-0">
<slot name="title">
<h2 class="stack-nav-title">{{ $t("stackListTitle") }}</h2>
<h2 class="font-heading text-sm font-semibold">{{ $t("stackListTitle") }}</h2>
</slot>
<router-link to="/compose" class="stack-nav-button stack-nav-primary" @click.left.exact="$emit('navigate')">
<font-awesome-icon icon="plus" aria-hidden="true" /> {{ $t("stackListNew") }}
</router-link>
<slot name="close" />
</div>
<div class="stack-nav-controls">
<label class="stack-nav-field">
<span>{{ $t("stackListSearch") }}</span>
<span class="stack-nav-search">
<font-awesome-icon icon="search" aria-hidden="true" />
<input ref="search" v-model.trim="searchText" type="search" :placeholder="$t('stackListSearchPlaceholder')" autocomplete="off">
</span>
</label>
<div class="stack-nav-filters">
<div class="stack-nav-field">
<label :for="hostId">{{ $t("stackListHost") }}</label>
<select :id="hostId" v-model="host">
<option :value="null">{{ $t("stackListAllHosts") }}</option>
<option v-for="agent in agents" :key="agent.endpoint" :value="agent.endpoint">
{{ agent.name }}
</option>
</select>
</div>
<div class="stack-nav-field">
<label :for="statusId">{{ $t("stackListStatus") }}</label>
<select :id="statusId" v-model="status">
<option value="">{{ $t("stackListAllStatuses") }}</option>
<option v-for="option in statuses" :key="option" :value="option">
{{ $t(option) }}
</option>
</select>
</div>
</div>
</div>
<div class="stack-nav-summary">
<span role="status">{{ loading ? $t("stackListLoading") : $t("stackListCount", resultCount) }}</span>
<button v-if="filtersActive" type="button" class="stack-nav-reset" @click="clearFilters">
{{ $t("stackListResetFilters") }}
</button>
</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") }}
<UiButton as-child size="sm">
<router-link to="/compose" @click.left.exact="$emit('navigate')">
<AppIcon name="plus" /> {{ $t("stackListNew") }}
</router-link>
</div>
</UiButton>
</div>
<Collapsible class="grid gap-2">
<div class="flex items-center gap-1.5">
<div class="relative min-w-0 flex-1">
<AppIcon name="search" class="pointer-events-none absolute start-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<UiInput ref="search" v-model.trim="searchText" type="search" :aria-label="$t('stackListSearch')" :placeholder="$t('stackListSearchPlaceholder')" class="ps-8" autocomplete="off" />
</div>
<CollapsibleTrigger as-child>
<UiButton variant="outline" size="icon" :aria-label="$t('toggleFilters')" :title="$t('toggleFilters')">
<PhFunnel :weight="filtersActive ? 'fill' : 'regular'" />
</UiButton>
</CollapsibleTrigger>
</div>
<CollapsibleContent class="grid grid-cols-2 gap-2">
<div class="grid min-w-0 gap-1.5">
<UiLabel :for="hostId">{{ $t("stackListHost") }}</UiLabel>
<UiNativeSelect :id="hostId" v-model="host" class="w-full min-w-0">
<option :value="null">{{ $t("stackListAllHosts") }}</option>
<option v-for="agent in agents" :key="agent.endpoint" :value="agent.endpoint">{{ agent.name }}</option>
</UiNativeSelect>
</div>
<div class="grid min-w-0 gap-1.5">
<UiLabel :for="statusId">{{ $t("stackListStatus") }}</UiLabel>
<UiNativeSelect :id="statusId" v-model="status" class="w-full min-w-0">
<option value="">{{ $t("stackListAllStatuses") }}</option>
<option v-for="option in statuses" :key="option" :value="option">{{ $t(option) }}</option>
</UiNativeSelect>
</div>
</CollapsibleContent>
</Collapsible>
<div class="flex min-h-6 items-center justify-between gap-2 text-xs text-muted-foreground">
<span role="status">{{ loading ? $t("stackListLoading") : $t("stackListCount", resultCount) }}</span>
<UiButton v-if="filtersActive" variant="ghost" size="xs" @click="clearFilters">{{ $t("stackListResetFilters") }}</UiButton>
</div>
<p v-if="!$root.socketIO.connected" class="text-sm text-muted-foreground" role="status">{{ $t("stackListStale") }}</p>
<div :key="filtersActive ? 'filtered' : 'all'" class="space-y-2">
<Collapsible v-for="agent in visibleAgents" :key="agent.endpoint" :default-open="true">
<CollapsibleTrigger v-if="agent.stacks.length" as-child>
<UiButton variant="ghost" size="sm" class="group w-full justify-start text-muted-foreground">
<AppIcon name="caret-down" class="group-data-[state=closed]:-rotate-90" />
<span class="min-w-0 truncate">{{ agent.name }}</span>
<UiBadge v-if="agent.connection !== 'online'" variant="outline" class="ms-auto">
{{ $t(agent.connection === "offline" ? "agentOffline" : "connecting") }}
</UiBadge>
</UiButton>
</CollapsibleTrigger>
<div v-else class="flex justify-between gap-2 px-2 py-1 text-xs text-muted-foreground">
<span class="truncate">{{ agent.name }}</span>
<UiBadge variant="outline">{{ $t(agent.connection === "offline" ? "agentOffline" : "connecting") }}</UiBadge>
</div>
<CollapsibleContent v-if="agent.stacks.length" as="ul" class="mt-1 space-y-0.5">
<li v-for="stack in agent.stacks" :key="stack.name">
<StackListItem :stack="stack" @navigate="$emit('navigate')" />
</li>
</CollapsibleContent>
</Collapsible>
</div>
<p v-if="emptyMessage" class="rounded-lg border border-dashed px-3 py-5 text-center text-sm text-muted-foreground">
{{ $t(emptyMessage) }}
</p>
</nav>
</template>
<script>
import { CollapsibleContent, CollapsibleRoot, CollapsibleTrigger } from "@ark-ui/vue/collapsible";
import { PhFunnel } from "@phosphor-icons/vue";
import { useId } from "vue";
import StackListItem from "./StackListItem.vue";
import { CREATED_FILE, CREATED_STACK, EXITED, RUNNING, UNKNOWN, statusNameShort } from "../../../common/util-common";
@ -96,9 +87,7 @@ const statusOrder = [ RUNNING, EXITED, CREATED_STACK, CREATED_FILE, UNKNOWN ];
export default {
components: {
CollapsibleContent,
CollapsibleRoot,
CollapsibleTrigger,
PhFunnel,
StackListItem,
},
emits: [ "navigate" ],
@ -210,7 +199,7 @@ export default {
this.searchText = "";
this.host = null;
this.status = "";
this.$refs.search.focus();
this.$refs.search?.$el.focus();
},
},
};

View File

@ -1,14 +1,13 @@
<template>
<router-link :to="url" class="stack-nav-item" @click.left.exact="$emit('navigate')">
<span class="stack-nav-item-copy">
<span class="stack-nav-name">{{ stack.name }}</span>
<span class="stack-nav-item-meta">
{{ hostName }}<template v-if="!stack.isManagedByDockge"> · {{ $t("stackListUnmanaged") }}</template>
</span>
</span>
<span class="stack-nav-badge" :data-state="status">
{{ $t(status) }}
<router-link
:to="url" class="flex min-w-0 items-center gap-2 rounded-lg px-2.5 py-2 text-sm hover:bg-sidebar-accent focus-visible:outline-2 focus-visible:outline-sidebar-ring"
exact-active-class="bg-sidebar-accent font-medium text-sidebar-accent-foreground" @click.left.exact="$emit('navigate')"
>
<span class="min-w-0 flex-1">
<span class="block truncate">{{ stack.name }}</span>
<span v-if="!stack.isManagedByDockge" class="block truncate text-xs text-muted-foreground">{{ $t("stackListUnmanaged") }}</span>
</span>
<UiBadge variant="outline" class="status-badge" :data-status="status">{{ $t(status) }}</UiBadge>
</router-link>
</template>
@ -22,11 +21,6 @@ export default {
type: Object,
required: true,
},
/** Display name of the host running the stack */
hostName: {
type: String,
required: true,
},
},
emits: [ "navigate" ],
computed: {

View File

@ -0,0 +1,128 @@
<template>
<UiCard>
<CardHeader>
<CardTitle>{{ $t("autoUpdateTitle") }}</CardTitle>
<CardDescription>{{ $t(supportsSchedule ? "autoUpdateDescription" : "autoUpdateLegacyDescription") }}</CardDescription>
</CardHeader>
<CardContent class="grid gap-5">
<form v-if="supportsSchedule" class="grid gap-4" @submit.prevent="save">
<div class="flex items-center gap-3">
<UiSwitch id="auto-update-enabled" v-model="enabled" :disabled="busy" />
<UiLabel for="auto-update-enabled">{{ $t("autoUpdateEnable") }}</UiLabel>
</div>
<div class="grid max-w-xl gap-3 sm:grid-cols-[10rem_minmax(0,1fr)]">
<div class="grid gap-1.5">
<UiLabel for="auto-update-time">{{ $t("autoUpdateTime") }}</UiLabel>
<UiInput id="auto-update-time" v-model="time" type="time" :disabled="busy" required />
</div>
<div class="grid gap-1.5">
<UiLabel for="auto-update-timezone">{{ $t("autoUpdateTimezone") }}</UiLabel>
<UiInput id="auto-update-timezone" v-model.trim="timezone" list="auto-update-timezones" :disabled="busy" required maxlength="100" />
<datalist id="auto-update-timezones">
<option v-for="zone in timezones" :key="zone" :value="zone" />
</datalist>
</div>
</div>
<div class="grid max-w-xl gap-2 border-t pt-4">
<div class="flex items-center gap-3">
<UiSwitch id="auto-update-delay" v-model="delayed" :disabled="busy" />
<UiLabel for="auto-update-delay">{{ $t("autoUpdateDelay") }}</UiLabel>
</div>
<p class="text-xs text-muted-foreground">{{ $t("autoUpdateDelayHelp") }}</p>
<div v-if="delayed" class="grid max-w-44 gap-1.5">
<UiLabel for="auto-update-delay-hours">{{ $t("autoUpdateDelayHours") }}</UiLabel>
<UiInput id="auto-update-delay-hours" v-model="delayHours" type="number" min="1" max="2160" step="1" :disabled="busy" required />
</div>
</div>
<UiButton type="submit" class="justify-self-start" :disabled="!dirty || busy">{{ $t("Save") }}</UiButton>
</form>
<div v-else class="flex items-center gap-3">
<UiSwitch id="auto-update-enabled" :model-value="policy.enabled" :disabled="busy" @update:model-value="$emit('save', $event)" />
<UiLabel for="auto-update-enabled">{{ $t("autoUpdateEnable") }}</UiLabel>
</div>
<div v-if="policy.nextRun || policy.lastRun || policy.pending?.length" class="grid gap-2 border-t pt-4 text-sm text-muted-foreground">
<p v-if="policy.nextRun">{{ $t("autoUpdateNextRun", { time: formatTime(policy.nextRun) }) }}</p>
<p v-if="policy.lastRun">
{{ $t("autoUpdateLastRun", { time: formatTime(policy.lastRun.at), result: $t("autoUpdateResult." + policy.lastRun.result) }) }}
</p>
<ul v-if="policy.pending?.length" class="grid gap-1">
<li v-for="item in policy.pending" :key="item.service">
{{ $t("autoUpdatePending", { service: item.service, time: formatTime(item.eligibleAt) }) }}
</li>
</ul>
</div>
</CardContent>
</UiCard>
</template>
<script>
const localZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const timezones = Array.from(new Set([ "UTC", localZone, ...(Intl.supportedValuesOf?.("timeZone") ?? []) ]));
export default {
props: {
policy: {
type: Object,
required: true,
},
busy: Boolean,
},
emits: [ "save" ],
data() {
return {
enabled: false,
time: "04:00",
timezone: "UTC",
delayed: false,
delayHours: 24,
timezones,
};
},
computed: {
supportsSchedule() {
return typeof this.policy.time === "string";
},
dirty() {
return this.enabled !== this.policy.enabled || this.time !== this.policy.time
|| this.timezone !== this.policy.timezone || (this.delayed ? Number(this.delayHours) : 0) !== this.policy.delayHours;
},
},
watch: {
policy: {
immediate: true,
handler(policy, previous) {
if (previous && [ "enabled", "time", "timezone", "delayHours" ].every(key => policy[key] === previous[key])) {
return;
}
this.enabled = policy.enabled;
this.time = policy.time ?? "04:00";
this.timezone = policy.timezone ?? "UTC";
this.delayed = Boolean(policy.delayHours);
this.delayHours = policy.delayHours || 24;
},
},
},
methods: {
save() {
this.$emit("save", {
enabled: this.enabled,
time: this.time,
timezone: this.timezone,
delayHours: this.delayed ? Number(this.delayHours) : 0,
});
},
formatTime(value) {
return new Date(value).toLocaleString(this.$i18n.locale, {
timeZone: this.policy.timezone || "UTC",
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
timeZoneName: "short",
});
},
},
};
</script>

View File

@ -1,6 +1,6 @@
<template>
<div class="shadow-box">
<div v-pre ref="terminal" class="main-terminal"></div>
<div class="terminal-shell">
<div v-pre ref="terminal" class="min-w-0"></div>
</div>
</template>
@ -101,7 +101,9 @@ export default {
// Bind to a div
this.terminal.open(this.$refs.terminal);
this.terminal.focus();
if (this.mode !== "displayOnly") {
this.terminal.focus();
}
// Add right-click context menu handler for paste
this.$refs.terminal.addEventListener("contextmenu", this.handleContextMenu);
@ -142,6 +144,7 @@ export default {
},
unmounted() {
this.terminalObserver?.disconnect();
window.removeEventListener("resize", this.onResizeEvent); // Remove the resize event listener from the window object.
this.$root.unbindTerminal(this.name);
this.terminal.dispose();
@ -281,6 +284,10 @@ export default {
window.addEventListener("resize", this.onResizeEvent);
}
this.terminalFitAddOn.fit();
if (!this.terminalObserver && this.$el.classList.contains("stack-log-terminal")) {
this.terminalObserver = new ResizeObserver(() => this.onResizeEvent());
this.terminalObserver.observe(this.$refs.terminal);
}
},
/**
* Handles the resize event of the terminal component.
@ -374,16 +381,3 @@ export default {
}
};
</script>
<style scoped lang="scss">
.main-terminal {
height: 100%;
}
</style>
<style lang="scss">
.terminal {
background-color: black !important;
height: 100%;
}
</style>

View File

@ -1,83 +1,48 @@
<template>
<form @submit.prevent="submit">
<div ref="modal" class="modal fade" tabindex="-1" data-bs-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
{{ $t("Setup 2FA") }}
<span v-if="twoFAStatus == true" class="badge bg-primary">{{ $t("Active") }}</span>
<span v-if="twoFAStatus == false" class="badge bg-primary">{{ $t("Inactive") }}</span>
</h5>
<button :disabled="processing" type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" />
</div>
<div class="modal-body">
<div class="mb-3">
<div v-if="uri && twoFAStatus == false" class="mx-auto text-center" style="width: 210px;">
<vue-qrcode :key="uri" :value="uri" type="image/png" :quality="1" :color="{ light: '#ffffffff' }" />
<button v-show="!showURI" type="button" class="btn btn-outline-primary btn-sm mt-2" @click="showURI = true">{{ $t("Show URI") }}</button>
</div>
<p v-if="showURI && twoFAStatus == false" class="text-break mt-2">{{ uri }}</p>
<div v-if="!(uri && twoFAStatus == false)" class="mb-3">
<label for="current-password" class="form-label">
{{ $t("Current Password") }}
</label>
<input
id="current-password"
v-model="currentPassword"
type="password"
class="form-control"
autocomplete="current-password"
required
/>
</div>
<button v-if="uri == null && twoFAStatus == false" class="btn btn-primary" type="button" @click="prepare2FA()">
{{ $t("Enable 2FA") }}
</button>
<button v-if="twoFAStatus == true" class="btn btn-danger" type="button" :disabled="processing" @click="confirmDisableTwoFA()">
{{ $t("Disable 2FA") }}
</button>
<div v-if="uri && twoFAStatus == false" class="mt-3">
<label for="basic-url" class="form-label">{{ $t("twoFAVerifyLabel") }}</label>
<div class="input-group">
<input v-model="token" type="text" maxlength="6" class="form-control" autocomplete="one-time-code" required>
<button class="btn btn-outline-primary" type="button" @click="verifyToken()">{{ $t("Verify Token") }}</button>
</div>
<p v-show="tokenValid" class="mt-2" style="color: green;">{{ $t("tokenValidSettingsMsg") }}</p>
</div>
</div>
</div>
<div v-if="uri && twoFAStatus == false" class="modal-footer">
<button type="submit" class="btn btn-primary" :disabled="processing || tokenValid == false" @click="confirmEnableTwoFA()">
<div v-if="processing" class="spinner-border spinner-border-sm me-1"></div>
{{ $t("Save") }}
</button>
<Dialog v-model:open="open">
<DialogContent :close-label="$t('Close')" :show-close-button="!processing" :aria-describedby="undefined" @pointer-down-outside.prevent @escape-key-down="processing && $event.preventDefault()">
<DialogHeader>
<DialogTitle>{{ $t("Setup 2FA") }}</DialogTitle>
</DialogHeader>
<div class="grid gap-3">
<UiBadge v-if="twoFAStatus !== null" variant="outline" class="status-badge" :data-status="twoFAStatus ? 'active' : 'inactive'">
{{ $t(twoFAStatus ? "Active" : "Inactive") }}
</UiBadge>
<div v-if="uri && !twoFAStatus" class="grid gap-2">
<vue-qrcode :key="uri" :value="uri" type="image/png" :quality="1" :color="{ light: '#ffffffff' }" class="mx-auto w-44 rounded-lg" />
<UiButton v-if="!showURI" variant="outline" class="justify-self-center" @click="showURI = true">{{ $t("Show URI") }}</UiButton>
<p v-else class="break-all font-mono text-xs text-muted-foreground">{{ uri }}</p>
<UiLabel for="verify-otp">{{ $t("twoFAVerifyLabel") }}</UiLabel>
<div class="flex gap-2">
<UiInput id="verify-otp" v-model="token" inputmode="numeric" maxlength="6" autocomplete="one-time-code" @update:model-value="tokenValid = false" />
<UiButton variant="outline" :disabled="processing || token?.length !== 6" @click="verifyToken">{{ $t("Verify Token") }}</UiButton>
</div>
<p v-if="tokenValid" class="text-sm text-muted-foreground">{{ $t("tokenValidSettingsMsg") }}</p>
</div>
<div v-else class="grid gap-2">
<UiLabel for="twofa-password">{{ $t("Current Password") }}</UiLabel>
<UiInput id="twofa-password" v-model="currentPassword" type="password" autocomplete="current-password" />
</div>
</div>
</div>
</form>
<Confirm ref="confirmEnableTwoFA" btn-style="btn-danger" :yes-text="$t('Yes')" :no-text="$t('No')" @yes="save2FA">
<DialogFooter>
<UiButton v-if="twoFAStatus" variant="destructive" :disabled="processing || !currentPassword" @click="confirmDisableTwoFA">{{ $t("Disable 2FA") }}</UiButton>
<UiButton v-else-if="uri" :disabled="processing || !tokenValid" @click="confirmEnableTwoFA">{{ $t("Save") }}</UiButton>
<UiButton v-else :disabled="processing || !currentPassword || twoFAStatus === null" @click="prepare2FA">{{ $t("Enable 2FA") }}</UiButton>
</DialogFooter>
</DialogContent>
</Dialog>
<Confirm ref="confirmEnableTwoFA" :yes-text="$t('Yes')" :no-text="$t('No')" @yes="save2FA">
{{ $t("confirmEnableTwoFAMsg") }}
</Confirm>
<Confirm ref="confirmDisableTwoFA" btn-style="btn-danger" :yes-text="$t('Yes')" :no-text="$t('No')" @yes="disable2FA">
<Confirm ref="confirmDisableTwoFA" destructive :yes-text="$t('Yes')" :no-text="$t('No')" @yes="disable2FA">
{{ $t("confirmDisableTwoFAMsg") }}
</Confirm>
</template>
<script lang="ts">
import { Modal } from "bootstrap";
import Confirm from "./Confirm.vue";
import VueQrcode from "vue-qrcode";
import { useToast } from "vue-toastification";
const toast = useToast();
import { toast } from "vue-sonner";
export default {
components: {
@ -87,6 +52,7 @@ export default {
props: {},
data() {
return {
open: false,
currentPassword: "",
processing: false,
uri: null,
@ -96,14 +62,16 @@ export default {
showURI: false,
};
},
mounted() {
this.modal = new Modal(this.$refs.modal);
this.getStatus();
},
methods: {
/** Show the dialog */
show() {
this.modal.show();
this.currentPassword = "";
this.uri = null;
this.token = null;
this.tokenValid = false;
this.showURI = false;
this.getStatus();
this.open = true;
},
/** Show dialog to confirm enabling 2FA */
@ -142,7 +110,7 @@ export default {
this.$root.toastRes(res);
this.getStatus();
this.currentPassword = "";
this.modal.hide();
this.open = false;
} else {
toast.error(res.msg);
}
@ -160,7 +128,7 @@ export default {
this.$root.toastRes(res);
this.getStatus();
this.currentPassword = "";
this.modal.hide();
this.open = false;
} else {
toast.error(res.msg);
}
@ -191,13 +159,3 @@ export default {
},
};
</script>
<style lang="scss" scoped>
@import "../styles/vars.scss";
.dark {
.modal-dialog .form-text, .modal-dialog p {
color: $dark-font-color;
}
}
</style>

View File

@ -1,9 +1,9 @@
<template>
<span :class="className">{{ statusName }}</span>
<UiBadge variant="outline" class="status-badge" :data-status="status">{{ $t(status) }}</UiBadge>
</template>
<script>
import { statusColor, statusNameShort } from "../../../common/util-common";
import { statusNameShort } from "../../../common/util-common";
export default {
props: {
@ -11,46 +11,13 @@ export default {
type: Object,
default: null,
},
fixedWidth: {
type: Boolean,
default: false,
},
},
computed: {
uptime() {
return this.$t("notAvailableShort");
},
color() {
return statusColor(this.stack?.status);
},
statusName() {
return this.$t(statusNameShort(this.stack?.status));
},
className() {
let className = `badge rounded-pill bg-${this.color}`;
if (this.fixedWidth) {
className += " fixed-width";
}
return className;
status() {
const name = statusNameShort(this.stack?.status);
return name === "?" ? "stackListUnknown" : name;
},
},
};
</script>
<style scoped>
.badge {
min-width: 62px;
}
.fixed-width {
width: 62px;
overflow: hidden;
text-overflow: ellipsis;
}
</style>

View File

@ -0,0 +1,82 @@
import type { App } from "vue";
import { AppIcon } from "../icon";
import { Alert } from "./ui/alert";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogHeader, AlertDialogFooter, AlertDialogTitle } from "./ui/alert-dialog";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "./ui/card";
import { Checkbox } from "./ui/checkbox";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "./ui/collapsible";
import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "./ui/dialog";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "./ui/dropdown-menu";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { NativeSelect } from "./ui/native-select";
import { Sheet, SheetContent, SheetTitle, SheetTrigger } from "./ui/sheet";
import { Toaster } from "./ui/sonner";
import { Switch } from "./ui/switch";
import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Textarea } from "./ui/textarea";
const components = {
AppIcon,
UiAlert: Alert,
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
UiBadge: Badge,
UiButton: Button,
UiCard: Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
UiCheckbox: Checkbox,
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
Dialog,
DialogClose,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
UiInput: Input,
UiLabel: Label,
UiNativeSelect: NativeSelect,
Sheet,
SheetContent,
SheetTitle,
SheetTrigger,
Toaster,
UiSwitch: Switch,
UiTable: Table,
TableBody,
TableCaption,
TableCell,
TableHead,
TableHeader,
TableRow,
Tabs,
TabsContent,
TabsList,
TabsTrigger,
UiTextarea: Textarea,
};
export function registerUi(app: App) {
for (const [ name, component ] of Object.entries(components)) {
app.component(name, component);
}
}

View File

@ -1,66 +1,22 @@
<template>
<div class="d-flex justify-content-center align-items-center">
<div class="logo d-flex flex-column justify-content-center align-items-center">
<object class="my-4" width="200" height="200" data="/icon.svg" />
<div class="fs-4 fw-bold">Dockge</div>
<div>{{ $t("Version") }}: {{ $root.info.version }}</div>
<div class="frontend-version">{{ $t("Frontend Version") }}: {{ $root.frontendVersion }}</div>
<div v-if="!$root.isFrontendBackendVersionMatched" class="alert alert-warning mt-4" role="alert">
⚠️ {{ $t("Frontend Version do not match backend version!") }}
</div>
<div class="my-3 update-link"><a href="https://github.com/louislam/dockge/releases" target="_blank" rel="noopener">{{ $t("Check Update On GitHub") }}</a></div>
<div class="mt-1">
<div class="form-check">
<label><input v-model="settings.checkUpdate" type="checkbox" @change="saveSettings()" /> {{ $t("Show update if available") }}</label>
</div>
<div class="form-check">
<label><input v-model="settings.checkBeta" type="checkbox" :disabled="!settings.checkUpdate" @change="saveSettings()" /> {{ $t("Also check beta release") }}</label>
</div>
</div>
<dl class="space-y-4 text-sm">
<div>
<dt class="font-medium">{{ $t("Version") }}</dt>
<dd class="mt-1 font-mono text-muted-foreground">{{ $root.info.version }}</dd>
</div>
</div>
<div>
<dt class="font-medium">{{ $t("Maintainer") }}</dt>
<dd class="mt-1 text-muted-foreground">Weapie</dd>
</div>
<div>
<dt class="font-medium">{{ $t("Original project") }}</dt>
<dd class="mt-1">
<a href="https://github.com/louislam/dockge" target="_blank" rel="noopener noreferrer" class="underline underline-offset-4">louislam/dockge</a>
</dd>
</div>
<div>
<dt class="font-medium">{{ $t("License") }}</dt>
<dd class="mt-1 text-muted-foreground">MIT</dd>
</div>
</dl>
</template>
<script>
export default {
computed: {
settings() {
return this.$parent.$parent.$parent.settings;
},
saveSettings() {
return this.$parent.$parent.$parent.saveSettings;
},
settingsLoaded() {
return this.$parent.$parent.$parent.settingsLoaded;
},
},
watch: {
}
};
</script>
<style lang="scss" scoped>
.logo {
margin: 4em 1em;
}
.update-link {
font-size: 0.8em;
}
.frontend-version {
font-size: 0.9em;
color: #cccccc;
.dark & {
color: #333333;
}
}
</style>

View File

@ -1,94 +1,20 @@
<template>
<div>
<div class="my-4">
<label for="language" class="form-label">
{{ $t("Language") }}
</label>
<select id="language" v-model="$root.language" class="form-select">
<option
v-for="(lang, i) in $i18n.availableLocales"
:key="`Lang${i}`"
:value="lang"
>
<div class="grid max-w-sm gap-5">
<div class="grid gap-2">
<UiLabel for="language">{{ $t("Language") }}</UiLabel>
<UiNativeSelect id="language" v-model="$root.language" class="w-full">
<option v-for="lang in $i18n.availableLocales" :key="lang" :value="lang">
{{ $i18n.messages[lang].languageName }}
</option>
</select>
</UiNativeSelect>
</div>
<div v-show="true" class="my-4">
<label for="timezone" class="form-label">{{ $t("Theme") }}</label>
<div>
<div
class="btn-group"
role="group"
aria-label="Basic checkbox toggle button group"
>
<input
id="btncheck1"
v-model="$root.userTheme"
type="radio"
class="btn-check"
name="theme"
autocomplete="off"
value="light"
/>
<label class="btn btn-outline-primary" for="btncheck1">
{{ $t("Light") }}
</label>
<input
id="btncheck2"
v-model="$root.userTheme"
type="radio"
class="btn-check"
name="theme"
autocomplete="off"
value="dark"
/>
<label class="btn btn-outline-primary" for="btncheck2">
{{ $t("Dark") }}
</label>
<input
id="btncheck3"
v-model="$root.userTheme"
type="radio"
class="btn-check"
name="theme"
autocomplete="off"
value="auto"
/>
<label class="btn btn-outline-primary" for="btncheck3">
{{ $t("Auto") }}
</label>
</div>
</div>
<div class="grid gap-2">
<UiLabel for="theme">{{ $t("Theme") }}</UiLabel>
<UiNativeSelect id="theme" v-model="$root.userTheme" class="w-full">
<option value="light">{{ $t("Light") }}</option>
<option value="dark">{{ $t("Dark") }}</option>
<option value="auto">{{ $t("Auto") }}</option>
</UiNativeSelect>
</div>
</div>
</template>
<script>
export default {
};
</script>
<style lang="scss" scoped>
@import "../../styles/vars.scss";
.btn-check:active + .btn-outline-primary,
.btn-check:checked + .btn-outline-primary,
.btn-check:hover + .btn-outline-primary {
color: #fff;
.dark & {
color: #000;
}
}
.dark {
.list-group-item {
background-color: $dark-bg2;
color: $dark-font-color;
}
}
</style>

View File

@ -0,0 +1,311 @@
<template>
<UiCard>
<CardHeader class="gap-4">
<div class="flex flex-wrap items-start justify-between gap-2">
<div class="grid gap-1">
<CardTitle class="text-lg">{{ $t(images ? "resourceImages" : "resourceVolumes") }}</CardTitle>
<CardDescription>{{ $t(images ? "resourceImagesDescription" : "resourceVolumesDescription") }}</CardDescription>
</div>
<UiButton variant="outline" :disabled="loading || Boolean(removing)" @click="load">
<AppIcon name="restart" /> {{ $t("resourceRefresh") }}
</UiButton>
</div>
<div class="flex flex-wrap gap-2">
<UiInput v-model.trim="search" type="search" :aria-label="$t('resourceSearch')" :placeholder="$t('resourceSearch')" class="w-full sm:max-w-xs" />
<UiNativeSelect v-model="usage" :aria-label="$t('stackListStatus')">
<option value="all">{{ $t("resourceAll") }}</option>
<option value="used">{{ $t("resourceUsed") }}</option>
<option value="unused">{{ $t("resourceUnused") }}</option>
<option v-if="images" value="updates">{{ $t("resourceUpdateAvailable") }}</option>
</UiNativeSelect>
<UiNativeSelect v-if="hosts.length > 1" v-model="endpoint" :aria-label="$t('stackListHost')">
<option v-for="host in hosts" :key="host.endpoint" :value="host.endpoint" :disabled="!host.online">{{ host.label }}</option>
</UiNativeSelect>
</div>
<ResourceCleanupControls
:key="kind + ':' + endpoint" :kind="kind" :endpoint="endpoint"
:host="hosts.find(host => host.endpoint === endpoint)?.label || endpoint"
:can-prune="!loading && !removing && items.some(item => !item.containers.length)"
@pruned="load"
/>
</CardHeader>
<CardContent class="grid gap-3" :aria-busy="loading">
<UiAlert v-if="error" variant="destructive">{{ $t(error) }}</UiAlert>
<p v-else-if="loading" class="text-sm text-muted-foreground" role="status">{{ $t("resourceLoading") }}</p>
<template v-else>
<p class="text-xs text-muted-foreground" role="status">{{ $t("resourceCount", { shown: visible.length, total: items.length }) }}</p>
<p v-if="!visible.length" class="rounded-lg border border-dashed p-5 text-center text-sm text-muted-foreground">
{{ $t(items.length ? "resourceNoMatches" : "resourceEmpty") }}
</p>
<ul v-else class="divide-y rounded-lg border">
<li v-for="item in visible" :key="key(item)">
<Collapsible>
<div class="grid gap-x-3 gap-y-2 p-3 sm:grid-cols-[minmax(0,1fr)_minmax(8rem,auto)_minmax(7rem,auto)_auto] sm:items-center">
<div class="min-w-0">
<p class="break-all font-mono text-sm font-medium">{{ title(item) }}</p>
<p class="mt-1 text-xs text-muted-foreground">
{{ images ? [ item.id.slice(7, 19), item.platform, item.referenceOnly ? $t("resourceReferenceOnly") : tagCount(item) ].filter(Boolean).join(" · ") : item.driver }}
</p>
</div>
<div class="flex flex-wrap items-center gap-1.5">
<UiBadge variant="outline">{{ $t(item.containers.length ? "resourceUsed" : "resourceUnused") }}</UiBadge>
<span v-if="item.containers.length" class="text-xs tabular-nums text-muted-foreground">{{ item.containers.length }}</span>
<UiBadge v-if="images && updateAvailable(item)" variant="secondary">{{ $t("resourceUpdateAvailable") }}</UiBadge>
</div>
<div class="text-xs text-muted-foreground sm:text-end">
<p v-if="images" class="tabular-nums">{{ formatSize(item.size) }}</p>
<p>{{ formatDate(item.created) }}</p>
</div>
<div class="flex justify-end gap-1">
<CollapsibleTrigger as-child>
<UiButton variant="ghost" size="sm" class="group">
{{ $t("resourceDetails") }}
<AppIcon name="caret-down" class="group-data-[state=open]:rotate-180" />
</UiButton>
</CollapsibleTrigger>
<UiButton
v-if="!item.containers.length && (!images || !item.tags.length)"
variant="ghost" size="icon-sm" class="text-destructive"
:aria-label="$t('deleteStack') + ' ' + title(item)" :disabled="Boolean(removing)"
@click="chooseRemoval(item)"
>
<AppIcon name="trash" />
</UiButton>
</div>
</div>
<CollapsibleContent class="grid gap-3 border-t bg-muted/20 p-3 text-sm">
<div v-if="item.containers.length" class="grid gap-1">
<p class="font-heading font-medium">{{ $tc("container", 2) }}</p>
<ul class="divide-y">
<li v-for="container in item.containers" :key="container.id" class="flex flex-wrap items-center justify-between gap-2 py-1.5">
<div class="min-w-0">
<p class="break-all font-mono text-xs">{{ container.name }}</p>
<p v-if="images && container.differentTagImage" class="mt-0.5 text-xs text-muted-foreground">{{ $t("resourceContainerDifferentImage") }}</p>
</div>
<UiBadge variant="outline" class="status-badge" :data-status="container.state">
{{ $t("resourceContainerState." + container.state, container.state) }}
</UiBadge>
</li>
</ul>
</div>
<p v-else class="text-xs text-muted-foreground">{{ $t("resourceNoReferences") }}</p>
<div v-if="images && item.tags.length" class="grid gap-1">
<p class="font-heading font-medium">{{ $t("resourceTags") }}</p>
<ul class="divide-y">
<li v-for="tag in item.tags" :key="tag" class="flex flex-wrap items-center gap-2 py-1.5">
<code class="min-w-0 flex-1 break-all text-xs">{{ tag }}</code>
<UiBadge variant="outline" role="status">{{ $t("resourceTagStatus." + (checks[tag] || "unchecked")) }}</UiBadge>
<UiButton variant="outline" size="sm" :disabled="Boolean(checking || removing)" @click="check(item, tag)">
{{ $t(checking === tag ? "resourceChecking" : "resourceCheckTag") }}
</UiButton>
<UiButton
v-if="!item.containers.length" variant="ghost" size="icon-sm" class="text-destructive"
:disabled="Boolean(removing)" :aria-label="$t('deleteStack') + ' ' + tag" @click="chooseRemoval(item, tag)"
>
<AppIcon name="trash" />
</UiButton>
</li>
</ul>
</div>
</CollapsibleContent>
</Collapsible>
</li>
</ul>
</template>
</CardContent>
</UiCard>
<ActionDialog
:model-value="Boolean(selection)" :title="$t('resourceDeleteTitle')" :action="$t('deleteStack')" destructive
@update:model-value="dialogOpenChanged" @confirm="removeSelected"
>
<p class="break-all font-mono">{{ selection?.name }}</p>
<p>{{ $t(images ? "resourceDeleteImageMessage" : "resourceDeleteVolumeMessage") }}</p>
</ActionDialog>
</template>
<script>
import ActionDialog from "../ActionDialog.vue";
import ResourceCleanupControls from "./ResourceCleanupControls.vue";
export default {
components: { ActionDialog,
ResourceCleanupControls },
props: {
kind: {
type: String,
required: true,
},
},
data() {
return {
endpoint: "",
usage: "all",
search: "",
items: [],
checks: {},
selection: null,
checking: "",
removing: null,
loading: true,
error: "",
generation: 0,
};
},
computed: {
images() {
return this.kind === "images";
},
hosts() {
const remote = Object.entries(this.$root.agentList).filter(([ endpoint ]) => endpoint).map(([ endpoint, agent ]) => ({
endpoint,
label: agent.name || endpoint,
online: this.$root.agentStatusList[endpoint] === "online",
}));
return [{ endpoint: "",
label: this.$t("stackListLocal"),
online: true }, ...remote ];
},
visible() {
const query = this.search.toLocaleLowerCase();
return this.items.filter(item => {
if (this.usage === "updates" && !this.updateAvailable(item)) {
return false;
}
if (this.usage === "used" && !item.containers.length || this.usage === "unused" && item.containers.length) {
return false;
}
return [ this.title(item), this.key(item), ...(item.tags || []), ...item.containers.map(container => container.name) ]
.some(value => value.toLocaleLowerCase().includes(query));
});
},
},
watch: {
endpoint: "load",
kind() {
this.usage = "all";
this.search = "";
this.load();
},
},
mounted() {
this.load();
},
beforeUnmount() {
this.generation++;
},
methods: {
key(item) {
return item.id || item.name;
},
title(item) {
return this.images ? item.tags[0] || (item.referenceOnly ? item.containers[0]?.reference : null) || this.$t("resourceUntagged") : item.name;
},
tagCount(item) {
return item.tags.length > 1 ? this.$t("resourceTagCount", { count: item.tags.length }) : "";
},
updateAvailable(item) {
return item.tags?.some(tag => this.checks[tag] === "updateAvailable");
},
formatDate(value) {
if (!value) {
return "–";
}
const date = new Date(value);
return Number.isFinite(date.getTime()) && date.getUTCFullYear() > 1 ? date.toLocaleDateString(this.$i18n.locale) : "–";
},
formatSize(bytes) {
if (bytes == null) {
return "–";
}
const mib = bytes / 1048576;
return new Intl.NumberFormat(this.$i18n.locale, { maximumFractionDigits: 1 }).format(mib >= 1024 ? mib / 1024 : mib)
+ (mib >= 1024 ? " GiB" : " MiB");
},
request(event, timeout, ...args) {
return this.$root.getSocket().timeout(timeout).emitWithAck("agent", this.endpoint, event, ...args);
},
async load() {
const generation = ++this.generation;
this.loading = true;
this.error = "";
this.items = [];
this.checks = {};
this.selection = null;
try {
const res = await this.request(this.images ? "listDockerImages" : "listDockerVolumes", 20000);
if (generation === this.generation) {
if (res.ok) {
this.items = res.items.sort((a, b) => this.title(a).localeCompare(this.title(b)));
this.checks = Object.assign({}, ...res.items.map(item => item.checks ?? {}));
} else {
this.error = res.msg || "resourceLoadFailed";
}
}
} catch {
if (generation === this.generation) {
this.error = "resourceLoadFailed";
}
} finally {
if (generation === this.generation) {
this.loading = false;
}
}
},
async check(item, tag) {
const generation = this.generation;
this.checking = tag;
try {
const res = await this.request("checkDockerImageTag", 65000, item.id, tag);
if (generation === this.generation) {
if (!res.ok) {
this.$root.toastRes(res);
}
this.checks[tag] = res.status || "unknown";
}
} catch {
if (generation === this.generation) {
this.checks[tag] = "unknown";
}
} finally {
this.checking = "";
}
},
chooseRemoval(item, tag = "") {
this.selection = { item,
tag,
name: tag || this.title(item) };
},
dialogOpenChanged(open) {
if (!open) {
// ActionDialog closes immediately before emitting confirm.
this.$nextTick(() => {
this.selection = null;
});
}
},
async removeSelected() {
if (!this.selection || this.removing) {
return;
}
const { item, tag } = this.selection;
this.removing = item;
const generation = this.generation;
try {
const res = this.images
? await this.request("removeDockerImage", 35000, item.id, tag)
: await this.request("removeDockerVolume", 35000, item.name, item.created);
this.$root.toastRes(res);
} catch {
this.$root.toastError("resourceDeleteFailed");
} finally {
this.removing = null;
if (generation === this.generation) {
await this.load();
}
}
},
},
};
</script>

View File

@ -1,114 +1,21 @@
<template>
<div>
<form class="my-4" autocomplete="off" @submit.prevent="saveGeneral">
<!-- Client side Timezone -->
<div v-if="false" class="mb-4">
<label for="timezone" class="form-label">
{{ $t("Display Timezone") }}
</label>
<select id="timezone" v-model="$root.userTimezone" class="form-select">
<option value="auto">
{{ $t("Auto") }}: {{ guessTimezone }}
</option>
<option
v-for="(timezone, index) in timezoneList"
:key="index"
:value="timezone.value"
>
{{ timezone.name }}
</option>
</select>
<form v-if="settingsPage.settingsLoaded" class="grid max-w-lg gap-4" autocomplete="off" @submit.prevent="settingsPage.saveSettings()">
<div class="grid gap-2">
<UiLabel for="primary-hostname">{{ $t("primaryHostname") }}</UiLabel>
<div class="flex gap-2">
<UiInput id="primary-hostname" v-model="settingsPage.settings.primaryHostname" :placeholder="$t('CurrentHostname')" />
<UiButton type="button" variant="outline" @click="settingsPage.settings.primaryHostname = hostname">
{{ $t("autoGet") }}
</UiButton>
</div>
<!-- Server Timezone -->
<div v-if="false" class="mb-4">
<label for="timezone" class="form-label">
{{ $t("Server Timezone") }}
</label>
<select id="timezone" v-model="settings.serverTimezone" class="form-select">
<option value="UTC">UTC</option>
<option
v-for="(timezone, index) in timezoneList"
:key="index"
:value="timezone.value"
>
{{ timezone.name }}
</option>
</select>
</div>
<!-- Primary Hostname -->
<div class="mb-4">
<label class="form-label" for="primaryBaseURL">
{{ $t("primaryHostname") }}
</label>
<div class="input-group mb-3">
<input
v-model="settings.primaryHostname"
class="form-control"
:placeholder="$t(`CurrentHostname`)"
/>
<button class="btn btn-outline-primary" type="button" @click="autoGetPrimaryHostname">
{{ $t("autoGet") }}
</button>
</div>
<div class="form-text"></div>
</div>
<!-- Save Button -->
<div>
<button class="btn btn-primary" type="submit">
{{ $t("Save") }}
</button>
</div>
</form>
</div>
</div>
<UiButton type="submit" class="justify-self-start">{{ $t("Save") }}</UiButton>
</form>
</template>
<script>
import dayjs from "dayjs";
import { timezoneList } from "../../util-frontend";
export default {
components: {
},
data() {
return {
timezoneList: timezoneList(),
};
},
computed: {
settings() {
return this.$parent.$parent.$parent.settings;
},
saveSettings() {
return this.$parent.$parent.$parent.saveSettings;
},
settingsLoaded() {
return this.$parent.$parent.$parent.settingsLoaded;
},
guessTimezone() {
return dayjs.tz.guess();
}
},
methods: {
/** Save the settings */
saveGeneral() {
localStorage.timezone = this.$root.userTimezone;
this.saveSettings();
},
/** Get the base URL of the application */
autoGetPrimaryHostname() {
this.settings.primaryHostname = location.hostname;
},
},
inject: [ "settingsPage" ],
data: () => ({ hostname: location.hostname }),
};
</script>

View File

@ -1,98 +1,42 @@
<template>
<div>
<div v-if="settingsLoaded" class="my-4">
<form class="my-4" autocomplete="off" @submit.prevent="saveGeneral">
<div class="shadow-box mb-3 editor-box edit-mode">
<code-mirror
ref="editor"
v-model="settings.globalENV"
:extensions="extensionsEnv"
minimal
wrap="true"
dark="true"
tab="true"
:hasFocus="editorFocus"
@change="onChange"
/>
</div>
<div class="my-4">
<!-- Save Button -->
<div>
<button class="btn btn-primary" type="submit">
{{ $t("Save") }}
</button>
</div>
</div>
</form>
<form v-if="settingsLoaded" class="grid gap-4" autocomplete="off" @submit.prevent="saveSettings">
<div class="env-editor overflow-hidden rounded-xl border">
<CodeMirror
v-model="settings.globalENV" :extensions="extensionsEnv" minimal wrap
:dark="$root.isDark" tab
/>
</div>
</div>
<UiButton type="submit" class="justify-self-start">{{ $t("Save") }}</UiButton>
</form>
</template>
<script>
import CodeMirror from "vue-codemirror6";
import { editorTheme } from "../../lib/editor-theme";
import { python } from "@codemirror/lang-python"; // good enough for .env key=value highlighting
import { dracula as editorTheme } from "thememirror";
import { lineNumbers, EditorView } from "@codemirror/view";
import { ref } from "vue";
import { lineNumbers } from "@codemirror/view";
export default {
name: "GlobalEnv",
components: {
CodeMirror,
},
inject: [ "settingsPage" ],
setup() {
const editorFocus = ref(false);
const focusEffectHandler = (state, focusing) => {
editorFocus.value = focusing;
return null;
};
const extensionsEnv = [
editorTheme,
python(),
lineNumbers(),
EditorView.focusChangeEffect.of(focusEffectHandler),
];
return { editorFocus,
extensionsEnv };
return { extensionsEnv: [ python(), lineNumbers(), ...editorTheme ] };
},
computed: {
settings() {
return this.$parent.$parent.$parent.settings;
return this.settingsPage.settings;
},
saveSettings() {
return this.$parent.$parent.$parent.saveSettings;
return this.settingsPage.saveSettings;
},
settingsLoaded() {
return this.$parent.$parent.$parent.settingsLoaded;
return this.settingsPage.settingsLoaded;
},
},
methods: {
/** Save the settings */
saveGeneral() {
this.saveSettings();
},
onChange() {
// hook for future live validation if desired
},
},
};
</script>
<style scoped lang="scss">
.editor-box {
font-family: 'JetBrains Mono', monospace;
font-size: 14px;
&.edit-mode {
background-color: #2c2f38 !important;
}
}
</style>

View File

@ -0,0 +1,164 @@
<template>
<section class="grid gap-3 border-t pt-4">
<div class="flex flex-wrap gap-2">
<UiButton variant="destructive" :disabled="!canPrune || pruning" @click="confirmOpen = true">
<AppIcon name="trash" /> {{ $t(pruning ? "resourceCleanupRunning" : "resourceCleanupAll") }}
</UiButton>
<UiButton variant="outline" :aria-expanded="scheduleOpen" @click="scheduleOpen = !scheduleOpen">
{{ $t("resourceCleanupAutomation") }}
<UiBadge v-if="schedule" variant="outline">{{ $t(schedule.enabled ? "Active" : "Inactive") }}</UiBadge>
</UiButton>
</div>
<div v-if="scheduleOpen" class="grid gap-3 rounded-lg border bg-muted/20 p-4">
<UiAlert v-if="loadError" variant="destructive">{{ $t("resourceLoadFailed") }}</UiAlert>
<p v-else-if="!schedule" class="text-sm text-muted-foreground" role="status">{{ $t("resourceLoading") }}</p>
<form v-else class="grid gap-3" @submit.prevent="save">
<div class="flex items-center gap-3">
<UiSwitch id="resource-cleanup-enabled" v-model="enabled" :disabled="saving" />
<UiLabel for="resource-cleanup-enabled">{{ $t("resourceCleanupEnable") }}</UiLabel>
</div>
<p class="max-w-prose text-sm text-muted-foreground">{{ $t(description, { host }) }}</p>
<div class="grid max-w-lg gap-3 sm:grid-cols-[10rem_minmax(0,1fr)]">
<div class="grid gap-1.5">
<UiLabel for="resource-cleanup-time">{{ $t("resourceCleanupTime") }}</UiLabel>
<UiInput id="resource-cleanup-time" v-model="time" type="time" :disabled="saving" required />
</div>
<div class="grid gap-1.5">
<UiLabel for="resource-cleanup-timezone">{{ $t("autoUpdateTimezone") }}</UiLabel>
<UiInput id="resource-cleanup-timezone" v-model.trim="timezone" list="resource-cleanup-zones" :disabled="saving" required maxlength="100" />
<datalist id="resource-cleanup-zones">
<option v-for="zone in timezones" :key="zone" :value="zone" />
</datalist>
</div>
</div>
<UiButton type="submit" class="justify-self-start" :disabled="saving || !dirty">{{ $t("Save") }}</UiButton>
<div class="grid gap-1 text-xs text-muted-foreground" aria-live="polite">
<p v-if="schedule.nextRun">{{ $t("resourceCleanupNext", { time: formatTime(schedule.nextRun) }) }}</p>
<p v-if="schedule.lastRun">{{ $t("resourceCleanupLast", { time: formatTime(schedule.lastRun.at), result: $t("resourceCleanupResult." + schedule.lastRun.result) }) }}</p>
</div>
</form>
</div>
</section>
<ActionDialog v-model="confirmOpen" :title="$t('resourceCleanupAll')" :action="$t('deleteStack')" destructive @confirm="prune">
<p>{{ $t(description, { host }) }}</p>
<p>{{ $t("resourceCleanupAllFilters") }}</p>
</ActionDialog>
</template>
<script>
import ActionDialog from "../ActionDialog.vue";
const timezones = Array.from(new Set([ "UTC", Intl.DateTimeFormat().resolvedOptions().timeZone, ...(Intl.supportedValuesOf?.("timeZone") ?? []) ]));
export default {
components: { ActionDialog },
props: {
kind: { type: String,
required: true },
endpoint: { type: String,
required: true },
host: { type: String,
required: true },
canPrune: Boolean,
},
emits: [ "pruned" ],
data() {
return {
confirmOpen: false,
scheduleOpen: false,
schedule: null,
enabled: false,
time: "04:00",
timezone: "UTC",
timezones,
saving: false,
pruning: false,
loadError: false,
};
},
computed: {
description() {
return this.kind === "images" ? "resourceCleanupImagesMessage" : "resourceCleanupVolumesMessage";
},
dirty() {
return this.schedule && (this.enabled !== this.schedule.enabled || this.time !== this.schedule.time
|| this.timezone !== this.schedule.timezone);
},
},
watch: {
scheduleOpen(open) {
if (open && !this.dirty) {
this.load();
}
},
},
mounted() {
this.load();
},
methods: {
request(event, timeout, ...args) {
return this.$root.getSocket().timeout(timeout).emitWithAck("agent", this.endpoint, event, this.kind, ...args);
},
apply(schedule) {
this.schedule = schedule;
this.enabled = schedule.enabled;
this.time = schedule.time;
this.timezone = schedule.timezone;
},
async load() {
this.loadError = false;
try {
const res = await this.request("getResourceCleanup", 15000);
if (res.ok && !this.dirty && !this.saving) {
this.apply(res.schedule);
}
this.loadError = !res.ok;
} catch {
this.loadError = true;
}
},
async save() {
this.saving = true;
try {
const res = await this.request("setResourceCleanup", 15000, {
enabled: this.enabled,
time: this.time,
timezone: this.timezone,
});
if (res.ok) {
this.apply(res.schedule);
this.$root.toastSuccess("Saved");
} else {
this.$root.toastRes(res);
}
} catch {
this.$root.toastError("resourceCleanupSaveFailed");
} finally {
this.saving = false;
}
},
async prune() {
if (!this.canPrune || this.pruning) {
return;
}
this.pruning = true;
try {
const res = await this.request("pruneDockerResources", 135000);
this.$root.toastRes(res);
} catch {
this.$root.toastError("resourceCleanupFailed");
} finally {
this.pruning = false;
this.$emit("pruned");
}
},
formatTime(at) {
return new Date(at).toLocaleString(this.$i18n.locale, {
timeZone: this.schedule.timezone,
dateStyle: "medium",
timeStyle: "short",
});
},
},
};
</script>

View File

@ -1,141 +1,64 @@
<template>
<div>
<div v-if="settingsLoaded" class="my-4">
<!-- Change Password -->
<template v-if="!settings.disableAuth">
<p>
{{ $t("Current User") }}: <strong>{{ $root.username }}</strong>
<button v-if="! settings.disableAuth" id="logout-btn" class="btn btn-danger ms-4 me-2 mb-2" @click="$root.logout">{{ $t("Logout") }}</button>
</p>
<h5 class="my-4 settings-subheading">{{ $t("Change Password") }}</h5>
<form class="mb-3" @submit.prevent="savePassword">
<div class="mb-3">
<label for="current-password" class="form-label">
{{ $t("Current Password") }}
</label>
<input
id="current-password"
v-model="password.currentPassword"
type="password"
class="form-control"
autocomplete="current-password"
required
/>
</div>
<div class="mb-3">
<label for="new-password" class="form-label">
{{ $t("New Password") }}
</label>
<input
id="new-password"
v-model="password.newPassword"
type="password"
class="form-control"
autocomplete="new-password"
required
/>
</div>
<div class="mb-3">
<label for="repeat-new-password" class="form-label">
{{ $t("Repeat New Password") }}
</label>
<input
id="repeat-new-password"
v-model="password.repeatNewPassword"
type="password"
class="form-control"
:class="{ 'is-invalid': invalidPassword }"
autocomplete="new-password"
required
/>
<div class="invalid-feedback">
{{ $t("passwordNotMatchMsg") }}
</div>
</div>
<div>
<button class="btn btn-primary" type="submit">
{{ $t("Update Password") }}
</button>
</div>
</form>
</template>
<!-- TODO: Hidden for now -->
<div v-if="! settings.disableAuth && false" class="mt-5 mb-3">
<h5 class="my-4 settings-subheading">
{{ $t("Two Factor Authentication") }}
</h5>
<div class="mb-4">
<button
class="btn btn-primary me-2"
type="button"
@click="$refs.TwoFADialog.show()"
>
{{ $t("2FA Settings") }}
</button>
<div v-if="settingsLoaded" class="grid max-w-lg gap-6">
<section v-if="!settings.disableAuth" class="grid gap-3">
<h2 class="section-title">{{ $t("Change Password") }}</h2>
<p class="text-sm text-muted-foreground">{{ $t("Current User") }} <strong class="text-foreground">{{ $root.username }}</strong></p>
<form class="grid gap-3" @submit.prevent="savePassword">
<div v-for="field in passwordFields" :key="field.key" class="grid gap-1.5">
<UiLabel :for="field.key">{{ $t(field.label) }}</UiLabel>
<UiInput
:id="field.key" v-model="password[field.key]" type="password" :autocomplete="field.autocomplete"
:aria-invalid="field.key === 'repeatNewPassword' && invalidPassword || undefined" required
/>
</div>
</div>
<div class="my-4">
<!-- Advanced -->
<h5 class="my-4 settings-subheading">{{ $t("Advanced") }}</h5>
<div class="mb-4">
<button v-if="settings.disableAuth" id="enableAuth-btn" class="btn btn-outline-primary me-2 mb-2" @click="enableAuth">{{ $t("Enable Auth") }}</button>
<button v-if="! settings.disableAuth" id="disableAuth-btn" class="btn btn-primary me-2 mb-2" @click="confirmDisableAuth">{{ $t("Disable Auth") }}</button>
</div>
</div>
</div>
<TwoFADialog ref="TwoFADialog" />
<Confirm ref="confirmDisableAuth" btn-style="btn-danger" :yes-text="$t('I understand, please disable')" :no-text="$t('Leave')" @yes="disableAuth">
<i18n-t keypath="disableauth.message1" tag="p">
<template #disableAuth>
<strong>{{ $t('disableAuth') }}</strong>
</template>
</i18n-t>
<i18n-t keypath="disableauth.message2" tag="p">
<template #scenarios>
<strong>{{ $t('scenarios') }}</strong>
</template>
</i18n-t>
<p>{{ $t("Please use this option carefully!") }}</p>
<div class="mb-3">
<label for="current-password2" class="form-label">
{{ $t("Current Password") }}
</label>
<input
id="current-password2"
v-model="password.currentPassword"
type="password"
class="form-control"
required
/>
</div>
</Confirm>
<p v-if="invalidPassword" class="text-sm text-destructive" role="alert">{{ $t("passwordNotMatchMsg") }}</p>
<UiButton type="submit" class="justify-self-start">{{ $t("Update Password") }}</UiButton>
</form>
</section>
<section class="grid gap-3 border-t pt-4">
<h2 class="section-title">{{ $t("Advanced") }}</h2>
<UiButton v-if="settings.disableAuth" id="enableAuth-btn" variant="outline" class="justify-self-start" @click="enableAuth">{{ $t("Enable Auth") }}</UiButton>
<UiButton v-else id="disableAuth-btn" variant="destructive" class="justify-self-start" @click="confirmDisableAuth">{{ $t("Disable Auth") }}</UiButton>
</section>
</div>
<Confirm ref="confirmDisableAuth" destructive :yes-text="$t('I understand, please disable')" :no-text="$t('Leave')" @yes="disableAuth">
<i18n-t keypath="disableauth.message1" tag="p">
<template #disableAuth><strong>{{ $t('disableAuth') }}</strong></template>
</i18n-t>
<i18n-t keypath="disableauth.message2" tag="p">
<template #scenarios><strong>{{ $t('scenarios') }}</strong></template>
</i18n-t>
<p>{{ $t("Please use this option carefully!") }}</p>
<div class="grid gap-2">
<UiLabel for="disable-auth-password">{{ $t("Current Password") }}</UiLabel>
<UiInput id="disable-auth-password" v-model="password.currentPassword" type="password" autocomplete="current-password" required />
</div>
</Confirm>
</template>
<script>
import Confirm from "../../components/Confirm.vue";
import TwoFADialog from "../../components/TwoFADialog.vue";
export default {
components: {
Confirm,
TwoFADialog
},
inject: [ "settingsPage" ],
data() {
return {
passwordFields: [
{ key: "currentPassword",
label: "Current Password",
autocomplete: "current-password" },
{ key: "newPassword",
label: "New Password",
autocomplete: "new-password" },
{ key: "repeatNewPassword",
label: "Repeat New Password",
autocomplete: "new-password" },
],
invalidPassword: false,
password: {
currentPassword: "",
@ -147,13 +70,13 @@ export default {
computed: {
settings() {
return this.$parent.$parent.$parent.settings;
return this.settingsPage.settings;
},
saveSettings() {
return this.$parent.$parent.$parent.saveSettings;
return this.settingsPage.saveSettings;
},
settingsLoaded() {
return this.$parent.$parent.$parent.settingsLoaded;
return this.settingsPage.settingsLoaded;
}
},

View File

@ -0,0 +1,15 @@
<script setup lang="ts">
import type { AlertDialogEmits, AlertDialogProps } from "reka-ui";
import { AlertDialogRoot, useForwardPropsEmits } from "reka-ui";
const props = defineProps<AlertDialogProps>();
const emits = defineEmits<AlertDialogEmits>();
const forwarded = useForwardPropsEmits(props, emits);
</script>
<template>
<AlertDialogRoot v-slot="slotProps" data-slot="alert-dialog" v-bind="forwarded">
<slot v-bind="slotProps" />
</AlertDialogRoot>
</template>

View File

@ -0,0 +1,33 @@
<script setup lang="ts">
import type { AlertDialogActionProps } from "reka-ui";
import type { HTMLAttributes } from "vue";
import type { ButtonVariants } from "@/components/ui/button";
import { reactiveOmit } from "@vueuse/core";
import { cn } from "@/lib/utils";
import { AlertDialogAction } from "reka-ui";
import { buttonVariants } from "@/components/ui/button";
const props = withDefaults(
defineProps<AlertDialogActionProps & {
class?: HTMLAttributes["class"]
variant?: ButtonVariants["variant"]
size?: ButtonVariants["size"]
}>(),
{
variant: "default",
size: "default",
},
);
const delegatedProps = reactiveOmit(props, "class", "variant", "size");
</script>
<template>
<AlertDialogAction
data-slot="alert-dialog-action"
v-bind="delegatedProps"
:class="cn('', buttonVariants({ variant, size }), props.class)"
>
<slot />
</AlertDialogAction>
</template>

View File

@ -0,0 +1,37 @@
<script setup lang="ts">
import type { AlertDialogCancelProps } from "reka-ui";
import type { HTMLAttributes } from "vue";
import type { ButtonVariants } from "@/components/ui/button";
import { reactiveOmit } from "@vueuse/core";
import { cn } from "@/lib/utils";
import { AlertDialogCancel } from "reka-ui";
import { buttonVariants } from "@/components/ui/button";
const props = withDefaults(
defineProps<AlertDialogCancelProps & {
class?: HTMLAttributes["class"]
variant?: ButtonVariants["variant"]
size?: ButtonVariants["size"]
}>(),
{
variant: "outline",
size: "default",
},
);
const delegatedProps = reactiveOmit(props, "class", "variant", "size");
</script>
<template>
<AlertDialogCancel
data-slot="alert-dialog-cancel"
v-bind="delegatedProps"
:class="cn(
'',
buttonVariants({ variant, size }),
props.class,
)"
>
<slot />
</AlertDialogCancel>
</template>

View File

@ -0,0 +1,53 @@
<script setup lang="ts">
import type { AlertDialogContentEmits, AlertDialogContentProps } from "reka-ui";
import type { HTMLAttributes } from "vue";
import { reactiveOmit } from "@vueuse/core";
import { cn } from "@/lib/utils";
import {
AlertDialogContent,
AlertDialogOverlay,
AlertDialogPortal,
useForwardPropsEmits,
} from "reka-ui";
defineOptions({
inheritAttrs: false,
});
const props = withDefaults(
defineProps<AlertDialogContentProps & {
class?: HTMLAttributes["class"]
size?: "default" | "sm"
}>(),
{
size: "default",
},
);
const emits = defineEmits<AlertDialogContentEmits>();
const delegatedProps = reactiveOmit(props, "class", "size");
const forwarded = useForwardPropsEmits(delegatedProps, emits);
</script>
<template>
<AlertDialogPortal>
<AlertDialogOverlay
data-slot="alert-dialog-overlay"
class="data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs fixed inset-0 z-50"
/>
<AlertDialogContent
data-slot="alert-dialog-content"
:data-size="size"
v-bind="{ ...$attrs, ...forwarded }"
:class="
cn(
'data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 bg-popover text-popover-foreground ring-foreground/10 gap-4 rounded-xl p-4 ring-1 duration-100 data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-sm group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 outline-none',
props.class,
)
"
>
<slot />
</AlertDialogContent>
</AlertDialogPortal>
</template>

View File

@ -0,0 +1,23 @@
<script setup lang="ts">
import type { AlertDialogDescriptionProps } from "reka-ui";
import type { HTMLAttributes } from "vue";
import { reactiveOmit } from "@vueuse/core";
import { cn } from "@/lib/utils";
import {
AlertDialogDescription,
} from "reka-ui";
const props = defineProps<AlertDialogDescriptionProps & { class?: HTMLAttributes["class"] }>();
const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
<AlertDialogDescription
data-slot="alert-dialog-description"
v-bind="delegatedProps"
:class="cn('text-muted-foreground *:[a]:hover:text-foreground text-sm text-balance md:text-pretty *:[a]:underline *:[a]:underline-offset-3', props.class)"
>
<slot />
</AlertDialogDescription>
</template>

View File

@ -0,0 +1,22 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import { cn } from "@/lib/utils";
const props = defineProps<{
class?: HTMLAttributes["class"]
}>();
</script>
<template>
<div
data-slot="alert-dialog-footer"
:class="
cn(
'bg-muted/50 -mx-4 -mb-4 rounded-b-xl border-t p-4 flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end',
props.class,
)
"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import { cn } from "@/lib/utils";
const props = defineProps<{
class?: HTMLAttributes["class"]
}>();
</script>
<template>
<div
data-slot="alert-dialog-header"
:class="cn('grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-4 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]', props.class)"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import { cn } from "@/lib/utils";
const props = defineProps<{
class?: HTMLAttributes["class"]
}>();
</script>
<template>
<div
data-slot="alert-dialog-media"
:class="cn('bg-muted mb-2 inline-flex size-10 items-center justify-center rounded-md sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*=size-])]:size-6', props.class)"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,21 @@
<script setup lang="ts">
import type { AlertDialogTitleProps } from "reka-ui";
import type { HTMLAttributes } from "vue";
import { reactiveOmit } from "@vueuse/core";
import { cn } from "@/lib/utils";
import { AlertDialogTitle } from "reka-ui";
const props = defineProps<AlertDialogTitleProps & { class?: HTMLAttributes["class"] }>();
const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
<AlertDialogTitle
data-slot="alert-dialog-title"
v-bind="delegatedProps"
:class="cn('text-base font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2 font-heading', props.class)"
>
<slot />
</AlertDialogTitle>
</template>

View File

@ -0,0 +1,12 @@
<script setup lang="ts">
import type { AlertDialogTriggerProps } from "reka-ui";
import { AlertDialogTrigger } from "reka-ui";
const props = defineProps<AlertDialogTriggerProps>();
</script>
<template>
<AlertDialogTrigger data-slot="alert-dialog-trigger" v-bind="props">
<slot />
</AlertDialogTrigger>
</template>

View File

@ -0,0 +1,10 @@
export { default as AlertDialog } from "./AlertDialog.vue";
export { default as AlertDialogAction } from "./AlertDialogAction.vue";
export { default as AlertDialogCancel } from "./AlertDialogCancel.vue";
export { default as AlertDialogContent } from "./AlertDialogContent.vue";
export { default as AlertDialogDescription } from "./AlertDialogDescription.vue";
export { default as AlertDialogFooter } from "./AlertDialogFooter.vue";
export { default as AlertDialogHeader } from "./AlertDialogHeader.vue";
export { default as AlertDialogMedia } from "./AlertDialogMedia.vue";
export { default as AlertDialogTitle } from "./AlertDialogTitle.vue";
export { default as AlertDialogTrigger } from "./AlertDialogTrigger.vue";

View File

@ -0,0 +1,21 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import type { AlertVariants } from ".";
import { cn } from "@/lib/utils";
import { alertVariants } from ".";
const props = defineProps<{
class?: HTMLAttributes["class"]
variant?: AlertVariants["variant"]
}>();
</script>
<template>
<div
data-slot="alert"
:class="cn(alertVariants({ variant }), props.class)"
role="alert"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import { cn } from "@/lib/utils";
const props = defineProps<{
class?: HTMLAttributes["class"]
}>();
</script>
<template>
<div
data-slot="alert-action"
:class="cn('absolute top-2 right-2', props.class)"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import { cn } from "@/lib/utils";
const props = defineProps<{
class?: HTMLAttributes["class"]
}>();
</script>
<template>
<div
data-slot="alert-description"
:class="cn('text-muted-foreground text-sm text-balance md:text-pretty [&_p:not(:last-child)]:mb-4 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground', props.class)"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import { cn } from "@/lib/utils";
const props = defineProps<{
class?: HTMLAttributes["class"]
}>();
</script>
<template>
<div
data-slot="alert-title"
:class="cn('font-medium group-has-[>svg]/alert:col-start-2 font-heading [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground', props.class)"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,21 @@
import type { VariantProps } from "class-variance-authority";
import { cva } from "class-variance-authority";
export { default as Alert } from "./Alert.vue";
export { default as AlertAction } from "./AlertAction.vue";
export { default as AlertDescription } from "./AlertDescription.vue";
export { default as AlertTitle } from "./AlertTitle.vue";
export const alertVariants = cva("grid gap-0.5 rounded-lg border px-2.5 py-2 text-left text-sm has-data-[slot=alert-action]:relative has-data-[slot=alert-action]:pr-18 has-[>svg]:grid-cols-[auto_1fr] has-[>svg]:gap-x-2 *:[svg]:row-span-2 *:[svg]:translate-y-0.5 *:[svg]:text-current *:[svg:not([class*=size-])]:size-4 group/alert relative w-full", {
variants: {
variant: {
default: "bg-card text-card-foreground",
destructive: "text-destructive bg-card *:data-[slot=alert-description]:text-destructive/90 *:[svg]:text-current",
},
},
defaultVariants: {
variant: "default",
},
});
export type AlertVariants = VariantProps<typeof alertVariants>

View File

@ -0,0 +1,27 @@
<script setup lang="ts">
import type { PrimitiveProps } from "reka-ui";
import type { HTMLAttributes } from "vue";
import type { BadgeVariants } from ".";
import { reactiveOmit } from "@vueuse/core";
import { cn } from "@/lib/utils";
import { Primitive } from "reka-ui";
import { badgeVariants } from ".";
const props = defineProps<PrimitiveProps & {
variant?: BadgeVariants["variant"]
class?: HTMLAttributes["class"]
}>();
const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
<Primitive
data-slot="badge"
:data-variant="variant"
:class="cn(badgeVariants({ variant }), props.class)"
v-bind="delegatedProps"
>
<slot />
</Primitive>
</template>

View File

@ -0,0 +1,24 @@
import type { VariantProps } from "class-variance-authority";
import { cva } from "class-variance-authority";
export { default as Badge } from "./Badge.vue";
export const badgeVariants = cva(
"h-5 gap-1 rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium transition-all has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&>svg]:size-3! group/badge inline-flex w-fit shrink-0 items-center justify-center overflow-hidden whitespace-nowrap focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
secondary: "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
destructive: "bg-destructive/10 [a]:hover:bg-destructive/20 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 text-destructive dark:bg-destructive/20",
outline: "border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
ghost: "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
link: "text-primary underline-offset-4 hover:underline",
},
},
defaultVariants: {
variant: "default",
},
},
);
export type BadgeVariants = VariantProps<typeof badgeVariants>

View File

@ -0,0 +1,31 @@
<script setup lang="ts">
import type { PrimitiveProps } from "reka-ui";
import type { HTMLAttributes } from "vue";
import type { ButtonVariants } from ".";
import { cn } from "@/lib/utils";
import { Primitive } from "reka-ui";
import { buttonVariants } from ".";
interface Props extends PrimitiveProps {
variant?: ButtonVariants["variant"]
size?: ButtonVariants["size"]
class?: HTMLAttributes["class"]
}
const props = withDefaults(defineProps<Props>(), {
as: "button",
});
</script>
<template>
<Primitive
data-slot="button"
:data-variant="variant"
:data-size="size"
:as="as"
:as-child="asChild"
:class="cn(buttonVariants({ variant, size }), props.class)"
>
<slot />
</Primitive>
</template>

View File

@ -0,0 +1,35 @@
import type { VariantProps } from "class-variance-authority";
import { cva } from "class-variance-authority";
export { default as Button } from "./Button.vue";
export const buttonVariants = cva(
"focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 rounded-lg border border-transparent bg-clip-padding text-sm font-medium focus-visible:ring-3 aria-invalid:ring-3 active:not-aria-[haspopup]:translate-y-px [&_svg:not([class*=size-])]:size-4 group/button inline-flex shrink-0 items-center justify-center whitespace-nowrap transition-all outline-none select-none disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
outline: "border-border bg-background hover:bg-muted hover:text-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50 aria-expanded:bg-muted aria-expanded:text-foreground",
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
ghost: "hover:bg-muted hover:text-foreground dark:hover:bg-muted/50 aria-expanded:bg-muted aria-expanded:text-foreground",
destructive: "bg-destructive/10 hover:bg-destructive/20 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/20 text-destructive focus-visible:border-destructive/40 dark:hover:bg-destructive/30",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
"default": "h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
"xs": "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*=size-])]:size-3",
"sm": "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*=size-])]:size-3.5",
"lg": "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
"icon": "size-8",
"icon-xs": "size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*=size-])]:size-3",
"icon-sm": "size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
"icon-lg": "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
},
);
export type ButtonVariants = VariantProps<typeof buttonVariants>

View File

@ -0,0 +1,21 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import { cn } from "@/lib/utils";
const props = withDefaults(defineProps<{
class?: HTMLAttributes["class"]
size?: "default" | "sm"
}>(), {
size: "default",
});
</script>
<template>
<div
data-slot="card"
:data-size="size"
:class="cn('ring-foreground/10 bg-card text-card-foreground gap-4 overflow-hidden rounded-xl py-4 text-sm ring-1 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl group/card flex flex-col', props.class)"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import { cn } from "@/lib/utils";
const props = defineProps<{
class?: HTMLAttributes["class"]
}>();
</script>
<template>
<div
data-slot="card-action"
:class="cn('col-start-2 row-span-2 row-start-1 self-start justify-self-end', props.class)"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import { cn } from "@/lib/utils";
const props = defineProps<{
class?: HTMLAttributes["class"]
}>();
</script>
<template>
<div
data-slot="card-content"
:class="cn('px-4 group-data-[size=sm]/card:px-3', props.class)"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import { cn } from "@/lib/utils";
const props = defineProps<{
class?: HTMLAttributes["class"]
}>();
</script>
<template>
<div
data-slot="card-description"
:class="cn('text-muted-foreground text-sm', props.class)"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import { cn } from "@/lib/utils";
const props = defineProps<{
class?: HTMLAttributes["class"]
}>();
</script>
<template>
<div
data-slot="card-footer"
:class="cn('bg-muted/50 rounded-b-xl border-t p-4 group-data-[size=sm]/card:p-3 flex items-center', props.class)"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import { cn } from "@/lib/utils";
const props = defineProps<{
class?: HTMLAttributes["class"]
}>();
</script>
<template>
<div
data-slot="card-header"
:class="cn('gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3 group/card-header @container/card-header grid auto-rows-min items-start has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto]', props.class)"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import { cn } from "@/lib/utils";
const props = defineProps<{
class?: HTMLAttributes["class"]
}>();
</script>
<template>
<div
data-slot="card-title"
:class="cn('text-base leading-snug font-medium group-data-[size=sm]/card:text-sm font-heading', props.class)"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,7 @@
export { default as Card } from "./Card.vue";
export { default as CardAction } from "./CardAction.vue";
export { default as CardContent } from "./CardContent.vue";
export { default as CardDescription } from "./CardDescription.vue";
export { default as CardFooter } from "./CardFooter.vue";
export { default as CardHeader } from "./CardHeader.vue";
export { default as CardTitle } from "./CardTitle.vue";

View File

@ -0,0 +1,34 @@
<script setup lang="ts">
import type { CheckboxRootEmits, CheckboxRootProps } from "reka-ui";
import type { HTMLAttributes } from "vue";
import { PhCheck } from "@phosphor-icons/vue";
import { reactiveOmit } from "@vueuse/core";
import { cn } from "@/lib/utils";
import { CheckboxIndicator, CheckboxRoot, useForwardPropsEmits } from "reka-ui";
const props = defineProps<CheckboxRootProps & { class?: HTMLAttributes["class"] }>();
const emits = defineEmits<CheckboxRootEmits>();
const delegatedProps = reactiveOmit(props, "class");
const forwarded = useForwardPropsEmits(delegatedProps, emits);
</script>
<template>
<CheckboxRoot
v-slot="slotProps"
data-slot="checkbox"
v-bind="forwarded"
:class="cn('border-input dark:bg-input/30 data-checked:bg-primary data-checked:text-primary-foreground dark:data-checked:bg-primary data-checked:border-primary aria-invalid:aria-checked:border-primary aria-invalid:border-destructive dark:aria-invalid:border-destructive/50 focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 flex size-4 items-center justify-center rounded-[4px] border transition-colors group-has-disabled/field:opacity-50 focus-visible:ring-3 aria-invalid:ring-3 peer relative shrink-0 outline-none after:absolute after:-inset-x-3 after:-inset-y-2 disabled:cursor-not-allowed disabled:opacity-50', props.class)"
>
<CheckboxIndicator
data-slot="checkbox-indicator"
class="[&>svg]:size-3.5 grid place-content-center text-current transition-none"
>
<slot v-bind="slotProps">
<PhCheck />
</slot>
</CheckboxIndicator>
</CheckboxRoot>
</template>

View File

@ -0,0 +1 @@
export { default as Checkbox } from "./Checkbox.vue";

View File

@ -0,0 +1,19 @@
<script setup lang="ts">
import type { CollapsibleRootEmits, CollapsibleRootProps } from "reka-ui";
import { CollapsibleRoot, useForwardPropsEmits } from "reka-ui";
const props = defineProps<CollapsibleRootProps>();
const emits = defineEmits<CollapsibleRootEmits>();
const forwarded = useForwardPropsEmits(props, emits);
</script>
<template>
<CollapsibleRoot
v-slot="slotProps"
data-slot="collapsible"
v-bind="forwarded"
>
<slot v-bind="slotProps" />
</CollapsibleRoot>
</template>

View File

@ -0,0 +1,15 @@
<script setup lang="ts">
import type { CollapsibleContentProps } from "reka-ui";
import { CollapsibleContent } from "reka-ui";
const props = defineProps<CollapsibleContentProps>();
</script>
<template>
<CollapsibleContent
data-slot="collapsible-content"
v-bind="props"
>
<slot />
</CollapsibleContent>
</template>

View File

@ -0,0 +1,15 @@
<script setup lang="ts">
import type { CollapsibleTriggerProps } from "reka-ui";
import { CollapsibleTrigger } from "reka-ui";
const props = defineProps<CollapsibleTriggerProps>();
</script>
<template>
<CollapsibleTrigger
data-slot="collapsible-trigger"
v-bind="props"
>
<slot />
</CollapsibleTrigger>
</template>

View File

@ -0,0 +1,3 @@
export { default as Collapsible } from "./Collapsible.vue";
export { default as CollapsibleContent } from "./CollapsibleContent.vue";
export { default as CollapsibleTrigger } from "./CollapsibleTrigger.vue";

View File

@ -0,0 +1,19 @@
<script setup lang="ts">
import type { DialogRootEmits, DialogRootProps } from "reka-ui";
import { DialogRoot, useForwardPropsEmits } from "reka-ui";
const props = defineProps<DialogRootProps>();
const emits = defineEmits<DialogRootEmits>();
const forwarded = useForwardPropsEmits(props, emits);
</script>
<template>
<DialogRoot
v-slot="slotProps"
data-slot="dialog"
v-bind="forwarded"
>
<slot v-bind="slotProps" />
</DialogRoot>
</template>

View File

@ -0,0 +1,15 @@
<script setup lang="ts">
import type { DialogCloseProps } from "reka-ui";
import { DialogClose } from "reka-ui";
const props = defineProps<DialogCloseProps>();
</script>
<template>
<DialogClose
data-slot="dialog-close"
v-bind="props"
>
<slot />
</DialogClose>
</template>

View File

@ -0,0 +1,53 @@
<script setup lang="ts">
import type { DialogContentEmits, DialogContentProps } from "reka-ui";
import type { HTMLAttributes } from "vue";
import { PhX } from "@phosphor-icons/vue";
import { reactiveOmit } from "@vueuse/core";
import { cn } from "@/lib/utils";
import {
DialogClose,
DialogContent,
DialogPortal,
useForwardPropsEmits,
} from "reka-ui";
import { Button } from "@/components/ui/button";
import DialogOverlay from "./DialogOverlay.vue";
defineOptions({
inheritAttrs: false,
});
const props = withDefaults(defineProps<DialogContentProps & { class?: HTMLAttributes["class"], showCloseButton?: boolean, closeLabel?: string }>(), {
showCloseButton: true,
closeLabel: "Close",
});
const emits = defineEmits<DialogContentEmits>();
const delegatedProps = reactiveOmit(props, "class", "showCloseButton", "closeLabel");
const forwarded = useForwardPropsEmits(delegatedProps, emits);
</script>
<template>
<DialogPortal>
<DialogOverlay />
<DialogContent
data-slot="dialog-content"
v-bind="{ ...$attrs, ...forwarded }"
:class="cn('bg-popover text-popover-foreground data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 data-closed:zoom-out-95 data-open:zoom-in-95 ring-foreground/10 grid max-w-[calc(100%-2rem)] gap-4 rounded-xl p-4 text-sm ring-1 duration-100 sm:max-w-sm fixed top-1/2 left-1/2 z-50 w-full -translate-x-1/2 -translate-y-1/2 outline-none', props.class)"
>
<slot />
<DialogClose
v-if="showCloseButton"
data-slot="dialog-close"
as-child
>
<Button variant="ghost" class="absolute top-2 right-2" size="icon-sm" :aria-label="closeLabel">
<PhX />
</Button>
</DialogClose>
</DialogContent>
</DialogPortal>
</template>

View File

@ -0,0 +1,23 @@
<script setup lang="ts">
import type { DialogDescriptionProps } from "reka-ui";
import type { HTMLAttributes } from "vue";
import { reactiveOmit } from "@vueuse/core";
import { cn } from "@/lib/utils";
import { DialogDescription, useForwardProps } from "reka-ui";
const props = defineProps<DialogDescriptionProps & { class?: HTMLAttributes["class"] }>();
const delegatedProps = reactiveOmit(props, "class");
const forwardedProps = useForwardProps(delegatedProps);
</script>
<template>
<DialogDescription
data-slot="dialog-description"
v-bind="forwardedProps"
:class="cn('text-muted-foreground *:[a]:hover:text-foreground text-sm *:[a]:underline *:[a]:underline-offset-3', props.class)"
>
<slot />
</DialogDescription>
</template>

View File

@ -0,0 +1,27 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import { cn } from "@/lib/utils";
import { DialogClose } from "reka-ui";
import { Button } from "@/components/ui/button";
const props = withDefaults(defineProps<{
class?: HTMLAttributes["class"]
showCloseButton?: boolean
}>(), {
showCloseButton: false,
});
</script>
<template>
<div
data-slot="dialog-footer"
:class="cn('bg-muted/50 -mx-4 -mb-4 rounded-b-xl border-t p-4 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', props.class)"
>
<slot />
<DialogClose v-if="showCloseButton" as-child>
<Button variant="outline">
Close
</Button>
</DialogClose>
</div>
</template>

View File

@ -0,0 +1,17 @@
<script setup lang="ts">
import type { HTMLAttributes } from "vue";
import { cn } from "@/lib/utils";
const props = defineProps<{
class?: HTMLAttributes["class"]
}>();
</script>
<template>
<div
data-slot="dialog-header"
:class="cn('gap-2 flex flex-col', props.class)"
>
<slot />
</div>
</template>

View File

@ -0,0 +1,21 @@
<script setup lang="ts">
import type { DialogOverlayProps } from "reka-ui";
import type { HTMLAttributes } from "vue";
import { reactiveOmit } from "@vueuse/core";
import { cn } from "@/lib/utils";
import { DialogOverlay } from "reka-ui";
const props = defineProps<DialogOverlayProps & { class?: HTMLAttributes["class"] }>();
const delegatedProps = reactiveOmit(props, "class");
</script>
<template>
<DialogOverlay
data-slot="dialog-overlay"
v-bind="delegatedProps"
:class="cn('data-open:animate-in data-closed:animate-out data-closed:fade-out-0 data-open:fade-in-0 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs fixed inset-0 isolate z-50', props.class)"
>
<slot />
</DialogOverlay>
</template>

View File

@ -0,0 +1,60 @@
<script setup lang="ts">
import type { DialogContentEmits, DialogContentProps } from "reka-ui";
import type { HTMLAttributes } from "vue";
import { PhX } from "@phosphor-icons/vue";
import { reactiveOmit } from "@vueuse/core";
import { cn } from "@/lib/utils";
import {
DialogClose,
DialogContent,
DialogOverlay,
DialogPortal,
useForwardPropsEmits,
} from "reka-ui";
defineOptions({
inheritAttrs: false,
});
const props = defineProps<DialogContentProps & { class?: HTMLAttributes["class"] }>();
const emits = defineEmits<DialogContentEmits>();
const delegatedProps = reactiveOmit(props, "class");
const forwarded = useForwardPropsEmits(delegatedProps, emits);
</script>
<template>
<DialogPortal>
<DialogOverlay
class="fixed inset-0 z-50 grid place-items-center overflow-y-auto bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"
>
<DialogContent
:class="
cn(
'relative z-50 grid w-full max-w-lg my-8 gap-4 border border-border bg-background p-6 shadow-lg duration-200 sm:rounded-lg md:w-full',
props.class,
)
"
v-bind="{ ...$attrs, ...forwarded }"
@pointer-down-outside="(event) => {
const originalEvent = event.detail.originalEvent;
const target = originalEvent.target as HTMLElement;
if (originalEvent.offsetX > target.clientWidth || originalEvent.offsetY > target.clientHeight) {
event.preventDefault();
}
}"
>
<slot />
<DialogClose
class="absolute top-4 right-4 p-0.5 transition-colors rounded-md hover:bg-secondary"
>
<PhX class="w-4 h-4" />
<span class="sr-only">Close</span>
</DialogClose>
</DialogContent>
</DialogOverlay>
</DialogPortal>
</template>

View File

@ -0,0 +1,23 @@
<script setup lang="ts">
import type { DialogTitleProps } from "reka-ui";
import type { HTMLAttributes } from "vue";
import { reactiveOmit } from "@vueuse/core";
import { cn } from "@/lib/utils";
import { DialogTitle, useForwardProps } from "reka-ui";
const props = defineProps<DialogTitleProps & { class?: HTMLAttributes["class"] }>();
const delegatedProps = reactiveOmit(props, "class");
const forwardedProps = useForwardProps(delegatedProps);
</script>
<template>
<DialogTitle
data-slot="dialog-title"
v-bind="forwardedProps"
:class="cn('text-base leading-none font-medium font-heading', props.class)"
>
<slot />
</DialogTitle>
</template>

View File

@ -0,0 +1,15 @@
<script setup lang="ts">
import type { DialogTriggerProps } from "reka-ui";
import { DialogTrigger } from "reka-ui";
const props = defineProps<DialogTriggerProps>();
</script>
<template>
<DialogTrigger
data-slot="dialog-trigger"
v-bind="props"
>
<slot />
</DialogTrigger>
</template>

Some files were not shown because too many files have changed in this diff Show More