mirror of
https://github.com/Finsys/dockhand.git
synced 2026-06-18 03:20:43 +03:00
Compare commits
110 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 50bc746660 | |||
| 81c03b5dc5 | |||
| 4a7c971cf8 | |||
| faa2b9d571 | |||
| 2ca41703f2 | |||
| c19d73c509 | |||
| 7e869b582a | |||
| d0e5edcc98 | |||
| a621f7abbc | |||
| 725798f327 | |||
| 83adb275cd | |||
| 80a9c8b60a | |||
| 07be45ace5 | |||
| f9bc2a13d1 | |||
| a84c11113c | |||
| 464fcb4231 | |||
| 0c894d906f | |||
| 1c16efd872 | |||
| 77ec974d09 | |||
| e9e521656c | |||
| c618328d83 | |||
| 76e8faef83 | |||
| 32c2919f05 | |||
| b2b4d3d975 | |||
| fa7f3be2f5 | |||
| c525a99d57 | |||
| 3f23dfb9f1 | |||
| e0548f69ef | |||
| d4eb5a5237 | |||
| c2b1708b66 | |||
| 5633e063e1 | |||
| eade47e962 | |||
| 3f99719cda | |||
| de243ce06d | |||
| dd0e778bf9 | |||
| 52de17e4e6 | |||
| 3140e4f074 | |||
| 988e65bd5b | |||
| a5360e9d53 | |||
| c9239f195a | |||
| 9daa647709 | |||
| 38fa758d8a | |||
| e829e60217 | |||
| 7ed20ece39 | |||
| 6149b3d935 | |||
| 139e798e77 | |||
| 2f7f5efc27 | |||
| 4cd7f1c4ef | |||
| 2e1cb7fdaf | |||
| a46154acf7 | |||
| 4627b70fcf | |||
| 54a14889de | |||
| 79c02984f0 | |||
| b2989d0aaf | |||
| f9fdfef4cb | |||
| 927858578b | |||
| afb0e734ee | |||
| 6122fa43da | |||
| 45bedca86d | |||
| 1aca2a10cb | |||
| 70e2166548 | |||
| ced84b583d | |||
| 53be8f8b20 | |||
| 236475577b | |||
| 7d6f6f2efd | |||
| 193dc44a71 | |||
| 1036cd0ec6 | |||
| 1a95f5ad05 | |||
| fd35a0adc0 | |||
| dd6c5fd3e5 | |||
| 0303f54e2b | |||
| 7f9862f9a0 | |||
| 750c9c1910 | |||
| 566d80019d | |||
| 261d94032c | |||
| 6cb948e84c | |||
| 80a5bbde99 | |||
| fd744ed9a2 | |||
| 6d9b509493 | |||
| e8ab07ec3f | |||
| 107e9c3758 | |||
| f972378117 | |||
| f588ed787b | |||
| 6baf6c23e8 | |||
| 6382b4083e | |||
| b269b8d50d | |||
| 410d542c58 | |||
| a02115e6bc | |||
| 86e4c9eb56 | |||
| c46870afd1 | |||
| a8a5623c10 | |||
| 059ecbb1dc | |||
| 3eab42169c | |||
| 6a7116a5b7 | |||
| 215f52b1f0 | |||
| de62327a07 | |||
| cd6544aedb | |||
| c60db2930c | |||
| 695acd922e | |||
| fcb36c4646 | |||
| 53ca99ac77 | |||
| 81fcc28d0b | |||
| 522154cd68 | |||
| 9db6e67a61 | |||
| ba05d16d79 | |||
| f4a57ecfd3 | |||
| ab8743bdae | |||
| e536388a7a | |||
| 497fbdb635 | |||
| 53d60fdddd |
+4
-4
@@ -37,7 +37,7 @@ RUN APKO_ARCH=$([ "$TARGETARCH" = "arm64" ] && echo "aarch64" || echo "x86_64")
|
||||
" - busybox" \
|
||||
" - tzdata" \
|
||||
" - docker-cli" \
|
||||
" - docker-compose=5.1.3-r0" \
|
||||
" - docker-compose=5.0.2-r1" \
|
||||
" - docker-cli-buildx" \
|
||||
" - sqlite" \
|
||||
" - postgresql-client" \
|
||||
@@ -77,8 +77,8 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
|
||||
# Copy package files and install dependencies (--ignore-scripts blocks malicious postinstall hooks)
|
||||
COPY package.json package-lock.json ./
|
||||
RUN MAKEFLAGS="-j$(nproc)" npm ci --ignore-scripts \
|
||||
&& MAKEFLAGS="-j$(nproc)" npm rebuild better-sqlite3 argon2
|
||||
RUN npm ci --ignore-scripts \
|
||||
&& npm rebuild better-sqlite3 argon2
|
||||
|
||||
# Copy source code and build
|
||||
COPY . .
|
||||
@@ -93,7 +93,7 @@ RUN cp -r node_modules/better-sqlite3/build /tmp/better-sqlite3-build \
|
||||
&& rm -rf node_modules/@types /tmp/better-sqlite3-build
|
||||
|
||||
# Build Go collector
|
||||
FROM --platform=$BUILDPLATFORM golang:1.25.9 AS go-builder
|
||||
FROM --platform=$BUILDPLATFORM golang:1.25.8 AS go-builder
|
||||
ARG TARGETARCH
|
||||
WORKDIR /app
|
||||
COPY collector/ ./collector/
|
||||
|
||||
+13
-26
@@ -18,33 +18,25 @@ FROM node:24-alpine AS app-builder
|
||||
WORKDIR /app
|
||||
|
||||
# Install build dependencies
|
||||
RUN apk add --no-cache git curl python3 make g++ gcc musl-dev
|
||||
RUN apk add --no-cache git curl python3 make g++
|
||||
|
||||
# Build getrandom shim for old kernels (< 3.17) that lack the syscall
|
||||
COPY shims/getrandom-shim.c /tmp/
|
||||
RUN gcc -shared -fPIC -O2 -o /tmp/libgetrandom-shim.so /tmp/getrandom-shim.c
|
||||
|
||||
# Copy package files and install dependencies (--ignore-scripts blocks malicious postinstall hooks)
|
||||
# Copy package files and install dependencies
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --ignore-scripts \
|
||||
&& npm rebuild better-sqlite3 argon2
|
||||
RUN npm ci
|
||||
|
||||
# Copy source code and build
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
# Production dependencies only
|
||||
# Preserve better-sqlite3 native addon (no prebuilds exist for Node 24 ABI 137)
|
||||
RUN cp -r node_modules/better-sqlite3/build /tmp/better-sqlite3-build \
|
||||
&& rm -rf node_modules \
|
||||
&& npm ci --omit=dev --ignore-scripts \
|
||||
&& cp -r /tmp/better-sqlite3-build node_modules/better-sqlite3/build \
|
||||
&& rm -rf node_modules/@types /tmp/better-sqlite3-build
|
||||
# Production dependencies only (rebuilds native addons against musl)
|
||||
RUN rm -rf node_modules \
|
||||
&& npm ci --omit=dev \
|
||||
&& rm -rf node_modules/@types
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Stage 2: Go Collector Builder
|
||||
# -----------------------------------------------------------------------------
|
||||
FROM golang:1.25.8 AS go-builder
|
||||
FROM golang:1.24 AS go-builder
|
||||
WORKDIR /app
|
||||
COPY collector/ ./collector/
|
||||
RUN cd collector && CGO_ENABLED=0 go build -o /app/bin/collection-worker .
|
||||
@@ -70,10 +62,9 @@ RUN apk add --no-cache \
|
||||
su-exec \
|
||||
libstdc++
|
||||
|
||||
# Create docker compose plugin symlink (skip if package already installed it there)
|
||||
# Create docker compose plugin symlink
|
||||
RUN mkdir -p /usr/libexec/docker/cli-plugins \
|
||||
&& [ -x /usr/libexec/docker/cli-plugins/docker-compose ] \
|
||||
|| ln -sf /usr/bin/docker-compose /usr/libexec/docker/cli-plugins/docker-compose
|
||||
&& ln -sf /usr/bin/docker-compose /usr/libexec/docker/cli-plugins/docker-compose
|
||||
|
||||
# Create dockhand user and group
|
||||
RUN addgroup -g 1001 dockhand \
|
||||
@@ -89,8 +80,7 @@ ENV SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt \
|
||||
DATA_DIR=/app/data \
|
||||
HOME=/home/dockhand \
|
||||
PUID=1001 \
|
||||
PGID=1001 \
|
||||
LD_PRELOAD=/usr/lib/libgetrandom-shim.so
|
||||
PGID=1001
|
||||
|
||||
# Copy application files with correct ownership
|
||||
COPY --from=app-builder --chown=dockhand:dockhand /app/node_modules ./node_modules
|
||||
@@ -108,9 +98,6 @@ COPY --chown=dockhand:dockhand drizzle-pg/ ./drizzle-pg/
|
||||
# Copy legal documents
|
||||
COPY --chown=dockhand:dockhand LICENSE.txt PRIVACY.txt ./
|
||||
|
||||
# Copy getrandom shim for old kernels (Synology DS1513+ with kernel 3.10.x)
|
||||
COPY --from=app-builder /tmp/libgetrandom-shim.so /usr/lib/libgetrandom-shim.so
|
||||
|
||||
# Copy entrypoint script
|
||||
COPY docker-entrypoint-node.sh /usr/local/bin/docker-entrypoint.sh
|
||||
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
|
||||
@@ -126,7 +113,7 @@ RUN mkdir -p /home/dockhand/.dockhand/stacks /app/data \
|
||||
EXPOSE 3000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
|
||||
CMD curl -f http://localhost:${PORT:-3000}/ || exit 1
|
||||
CMD curl -f http://localhost:3000/ || exit 1
|
||||
|
||||
ENTRYPOINT ["/sbin/tini", "--", "/usr/local/bin/docker-entrypoint.sh"]
|
||||
CMD []
|
||||
CMD ["node", "/app/server.js"]
|
||||
|
||||
@@ -36,12 +36,6 @@ Dockhand is a modern, efficient Docker management application providing real-tim
|
||||
- **Database**: SQLite or PostgreSQL via Drizzle ORM
|
||||
- **Docker**: direct docker API calls.
|
||||
|
||||
## Screenshots
|
||||
| Light Mode | Dark Mode |
|
||||
| --- | --- |
|
||||
| <img src="docs/dashboard1.webp" width="600" alt="Dashboard 1 Light"> | <img src="docs/dashboard2.webp" width="600" alt="Dashboard 2 Dark"> |
|
||||
| <img src="docs/dashboard3.webp" width="600" alt="Dashboard 3 Light"> | <img src="docs/dashboard4.webp" width="600" alt="Dashboard 4 Dark"> |
|
||||
|
||||
## License
|
||||
|
||||
Dockhand is licensed under the [Business Source License 1.1](LICENSE.txt) (BSL 1.1).
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
module github.com/Finsys/dockhand/collector
|
||||
|
||||
go 1.25.9
|
||||
go 1.25
|
||||
|
||||
@@ -10,7 +10,7 @@ PGID=${PGID:-1001}
|
||||
export BODY_SIZE_LIMIT=${BODY_SIZE_LIMIT:-2G}
|
||||
|
||||
# Default command (--expose-gc allows forced GC from /api/debug/memory?gc=true)
|
||||
# Custom CA: set NODE_EXTRA_CA_CERTS=/path/to/ca.crt (appends to built-in CAs, git ops auto-merge with system CAs)
|
||||
# Custom CA: set NODE_EXTRA_CA_CERTS=/path/to/ca.crt (appends to built-in CAs)
|
||||
# Enterprise (system CA store): set NODE_OPTIONS="--use-openssl-ca"
|
||||
if [ "$MEMORY_MONITOR" = "true" ]; then
|
||||
DEFAULT_CMD="node --dns-result-order=ipv4first --no-network-family-autoselection --expose-gc /app/server.js"
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 292 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 224 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 283 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 281 KiB |
@@ -1,21 +0,0 @@
|
||||
CREATE TABLE IF NOT EXISTS "api_tokens" (
|
||||
"id" serial PRIMARY KEY NOT NULL,
|
||||
"user_id" integer NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"token_hash" text NOT NULL,
|
||||
"token_prefix" text NOT NULL,
|
||||
"last_used" timestamp,
|
||||
"expires_at" timestamp,
|
||||
"created_at" timestamp DEFAULT now(),
|
||||
"updated_at" timestamp DEFAULT now(),
|
||||
CONSTRAINT "api_tokens_token_hash_unique" UNIQUE("token_hash")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
DO $$ BEGIN
|
||||
ALTER TABLE "api_tokens" ADD CONSTRAINT "api_tokens_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
|
||||
EXCEPTION
|
||||
WHEN duplicate_object THEN null;
|
||||
END $$;
|
||||
--> statement-breakpoint
|
||||
CREATE INDEX IF NOT EXISTS "api_tokens_user_id_idx" ON "api_tokens" USING btree ("user_id");--> statement-breakpoint
|
||||
CREATE INDEX IF NOT EXISTS "api_tokens_token_prefix_idx" ON "api_tokens" USING btree ("token_prefix");
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"id": "cefce4cc-994a-4b79-b55a-e995211b8f6a",
|
||||
"prevId": "b10cba96-4947-484f-84a2-efb65205381f",
|
||||
"id": "b10cba96-4947-484f-84a2-efb65205381f",
|
||||
"prevId": "eef8322a-0ccc-418c-b0f6-f51972a1850e",
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"tables": {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -36,13 +36,6 @@
|
||||
"when": 1774155653752,
|
||||
"tag": "0004_add_git_stack_deploy_options",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 5,
|
||||
"version": "7",
|
||||
"when": 1775312212996,
|
||||
"tag": "0005_add_api_tokens",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
CREATE TABLE `api_tokens` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`user_id` integer NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`token_hash` text NOT NULL,
|
||||
`token_prefix` text NOT NULL,
|
||||
`last_used` text,
|
||||
`expires_at` text,
|
||||
`created_at` text DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` text DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `api_tokens_token_hash_unique` ON `api_tokens` (`token_hash`);--> statement-breakpoint
|
||||
CREATE INDEX `api_tokens_user_id_idx` ON `api_tokens` (`user_id`);--> statement-breakpoint
|
||||
CREATE INDEX `api_tokens_token_prefix_idx` ON `api_tokens` (`token_prefix`);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -36,13 +36,6 @@
|
||||
"when": 1774155653752,
|
||||
"tag": "0004_add_git_stack_deploy_options",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 5,
|
||||
"version": "6",
|
||||
"when": 1775311743346,
|
||||
"tag": "0005_add_api_tokens",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
+4
-5
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "dockhand",
|
||||
"private": true,
|
||||
"version": "1.0.27",
|
||||
"version": "1.0.23",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "npx vite dev",
|
||||
@@ -77,11 +77,11 @@
|
||||
"croner": "9.1.0",
|
||||
"cronstrue": "3.9.0",
|
||||
"devalue": "5.6.4",
|
||||
"drizzle-orm": "0.45.2",
|
||||
"drizzle-orm": "0.45.1",
|
||||
"fast-xml-parser": "5.5.8",
|
||||
"js-yaml": "4.1.1",
|
||||
"ldapts": "8.1.3",
|
||||
"nodemailer": "8.0.5",
|
||||
"nodemailer": "8.0.4",
|
||||
"otpauth": "9.4.1",
|
||||
"postgres": "3.4.8",
|
||||
"qrcode": "1.5.4",
|
||||
@@ -136,7 +136,6 @@
|
||||
"@codemirror/commands": "6.10.1",
|
||||
"@codemirror/search": "6.6.0",
|
||||
"@lezer/common": "1.5.0",
|
||||
"@lezer/highlight": "1.2.3",
|
||||
"devalue": "5.6.4"
|
||||
"@lezer/highlight": "1.2.3"
|
||||
}
|
||||
}
|
||||
|
||||
+7
-91
@@ -4,8 +4,6 @@ import { initDatabase, hasAdminUser } from '$lib/server/db';
|
||||
import { startSubprocesses, stopSubprocesses } from '$lib/server/subprocess-manager';
|
||||
import { startScheduler } from '$lib/server/scheduler';
|
||||
import { isAuthEnabled, validateSession } from '$lib/server/auth';
|
||||
import { validateApiToken } from '$lib/server/api-tokens';
|
||||
import { requestContext } from '$lib/server/request-context';
|
||||
import { setServerStartTime } from '$lib/server/uptime';
|
||||
import { checkLicenseExpiry, getHostname } from '$lib/server/license';
|
||||
import { initCryptoFallback } from '$lib/server/crypto-fallback';
|
||||
@@ -200,58 +198,6 @@ if (!initialized) {
|
||||
}
|
||||
}
|
||||
|
||||
// Bearer token auth failure rate limiting (per IP, 5-minute cooldown after 10 failures)
|
||||
const bearerFailCounts = new Map<string, { count: number; firstFail: number }>();
|
||||
const BEARER_FAIL_WINDOW_MS = 60_000; // 1-minute sliding window
|
||||
const BEARER_FAIL_MAX = 15; // max failures per window
|
||||
const BEARER_COOLDOWN_MS = 5 * 60 * 1000; // 5-minute cooldown after exceeding limit
|
||||
const bearerCooldowns = new Map<string, number>(); // IP → cooldown-until timestamp
|
||||
|
||||
// Periodic cleanup
|
||||
setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [ip, until] of bearerCooldowns) {
|
||||
if (now > until) bearerCooldowns.delete(ip);
|
||||
}
|
||||
for (const [ip, entry] of bearerFailCounts) {
|
||||
if (now - entry.firstFail > BEARER_FAIL_WINDOW_MS) bearerFailCounts.delete(ip);
|
||||
}
|
||||
}, BEARER_COOLDOWN_MS).unref?.();
|
||||
|
||||
function getClientIp(event: { request: Request; getClientAddress?: () => string }): string {
|
||||
// Prefer socket-level IP (SvelteKit resolves proxy headers via adapter config)
|
||||
// This prevents X-Forwarded-For spoofing to bypass rate limiting
|
||||
try {
|
||||
const addr = event.getClientAddress?.();
|
||||
if (addr) return addr;
|
||||
} catch { /* getClientAddress may throw if unavailable */ }
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
function recordBearerFailure(ip: string): void {
|
||||
const now = Date.now();
|
||||
const entry = bearerFailCounts.get(ip);
|
||||
if (!entry || now - entry.firstFail > BEARER_FAIL_WINDOW_MS) {
|
||||
bearerFailCounts.set(ip, { count: 1, firstFail: now });
|
||||
return;
|
||||
}
|
||||
entry.count++;
|
||||
if (entry.count >= BEARER_FAIL_MAX) {
|
||||
bearerCooldowns.set(ip, now + BEARER_COOLDOWN_MS);
|
||||
bearerFailCounts.delete(ip);
|
||||
}
|
||||
}
|
||||
|
||||
function isBearerRateLimited(ip: string): boolean {
|
||||
const until = bearerCooldowns.get(ip);
|
||||
if (!until) return false;
|
||||
if (Date.now() > until) {
|
||||
bearerCooldowns.delete(ip);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Routes that don't require authentication
|
||||
const PUBLIC_PATHS = [
|
||||
'/login',
|
||||
@@ -301,51 +247,21 @@ export const handle: Handle = async ({ event, resolve }) => {
|
||||
// Check if auth is enabled
|
||||
const authEnabled = await isAuthEnabled();
|
||||
|
||||
// If auth is disabled, allow everything
|
||||
// If auth is disabled, allow everything (app works as before)
|
||||
if (!authEnabled) {
|
||||
event.locals.user = null;
|
||||
event.locals.authEnabled = false;
|
||||
const ctx = { user: null, authEnabled: false, authMethod: 'none' as const };
|
||||
return requestContext.run(ctx, async () => compressResponse(event.request, await resolve(event)));
|
||||
}
|
||||
|
||||
// Auth is enabled - check session first
|
||||
let user = await validateSession(event.cookies);
|
||||
let authMethod: 'cookie' | 'bearer' | 'none' = user ? 'cookie' : 'none';
|
||||
|
||||
// If no session, try Bearer token on API routes
|
||||
if (!user && event.url.pathname.startsWith('/api/')) {
|
||||
const authHeader = event.request.headers.get('authorization');
|
||||
if (authHeader && authHeader.startsWith('Bearer dh_') && authHeader.length <= 207) {
|
||||
const clientIp = getClientIp(event);
|
||||
|
||||
// Rate limit failed Bearer attempts
|
||||
if (isBearerRateLimited(clientIp)) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: 'Too many failed authentication attempts' }),
|
||||
{ status: 429, headers: { 'Content-Type': 'application/json', 'Retry-After': '300' } }
|
||||
);
|
||||
}
|
||||
|
||||
const token = authHeader.substring(7); // strip "Bearer "
|
||||
user = await validateApiToken(token);
|
||||
|
||||
if (user) {
|
||||
authMethod = 'bearer';
|
||||
} else {
|
||||
recordBearerFailure(clientIp);
|
||||
}
|
||||
}
|
||||
return compressResponse(event.request, await resolve(event));
|
||||
}
|
||||
|
||||
// Auth is enabled - check session
|
||||
const user = await validateSession(event.cookies);
|
||||
event.locals.user = user;
|
||||
event.locals.authEnabled = true;
|
||||
|
||||
const ctx = { user, authEnabled: true, authMethod };
|
||||
|
||||
// Public paths don't require authentication
|
||||
if (isPublicPath(event.url.pathname)) {
|
||||
return requestContext.run(ctx, async () => compressResponse(event.request, await resolve(event)));
|
||||
return compressResponse(event.request, await resolve(event));
|
||||
}
|
||||
|
||||
// If not authenticated
|
||||
@@ -354,7 +270,7 @@ export const handle: Handle = async ({ event, resolve }) => {
|
||||
// This enables the first admin user to be created during initial setup
|
||||
const noAdminSetupMode = !(await hasAdminUser());
|
||||
if (noAdminSetupMode && event.url.pathname === '/api/users' && event.request.method === 'POST') {
|
||||
return requestContext.run(ctx, async () => compressResponse(event.request, await resolve(event)));
|
||||
return compressResponse(event.request, await resolve(event));
|
||||
}
|
||||
|
||||
// API routes return 401
|
||||
@@ -373,7 +289,7 @@ export const handle: Handle = async ({ event, resolve }) => {
|
||||
redirect(307, `/login?redirect=${redirectUrl}`);
|
||||
}
|
||||
|
||||
return requestContext.run(ctx, async () => compressResponse(event.request, await resolve(event)));
|
||||
return compressResponse(event.request, await resolve(event));
|
||||
} finally {
|
||||
rssAfterOp('http', httpBefore);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
onConfirm: () => void;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
children: Snippet<[{ open: boolean }]>;
|
||||
extraContent?: Snippet;
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -36,8 +35,7 @@
|
||||
disabled = false,
|
||||
onConfirm,
|
||||
onOpenChange,
|
||||
children,
|
||||
extraContent
|
||||
children
|
||||
}: Props = $props();
|
||||
|
||||
const triggerClass = $derived(unstyled
|
||||
@@ -105,16 +103,11 @@
|
||||
align={position === 'left' ? 'start' : 'end'}
|
||||
sideOffset={8}
|
||||
>
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-xs whitespace-nowrap">{action} {itemType} {#if displayName}<strong>{displayName}</strong>{/if}?</span>
|
||||
<Button size="sm" {variant} class="h-6 px-2 text-xs" onclick={handleConfirm}>
|
||||
{confirmText}
|
||||
</Button>
|
||||
</div>
|
||||
{#if extraContent}
|
||||
{@render extraContent()}
|
||||
{/if}
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-xs whitespace-nowrap">{action} {itemType} {#if displayName}<strong>{displayName}</strong>{/if}?</span>
|
||||
<Button size="sm" {variant} class="h-6 px-2 text-xs" onclick={handleConfirm}>
|
||||
{confirmText}
|
||||
</Button>
|
||||
</div>
|
||||
</Popover.Content>
|
||||
</Popover.Root>
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
<script lang="ts">
|
||||
import { Sun, Moon } from 'lucide-svelte';
|
||||
import { getTimeFormat } from '$lib/stores/settings';
|
||||
|
||||
interface Props {
|
||||
logs: string | null;
|
||||
darkMode?: boolean;
|
||||
timezone?: string;
|
||||
onToggleTheme?: () => void;
|
||||
}
|
||||
|
||||
let { logs, darkMode = true, timezone, onToggleTheme }: Props = $props();
|
||||
let { logs, darkMode = true, onToggleTheme }: Props = $props();
|
||||
|
||||
// Parse log lines with timestamp and content
|
||||
function parseLogLine(line: string): { timestamp: string; content: string; type: 'trivy' | 'grype' | 'error' | 'default' } {
|
||||
@@ -46,15 +44,7 @@
|
||||
}
|
||||
|
||||
function formatTimestamp(timestamp: string): string {
|
||||
const d = new Date(timestamp);
|
||||
if (isNaN(d.getTime())) return timestamp;
|
||||
return new Intl.DateTimeFormat('en-GB', {
|
||||
timeZone: timezone || undefined,
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: getTimeFormat() === '12h'
|
||||
}).format(d);
|
||||
return timestamp.split('T')[1]?.replace('Z', '') || timestamp;
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
// Detect schedule type from cron expression
|
||||
function detectScheduleType(cron: string): 'daily' | 'weekly' | 'custom' {
|
||||
const parts = cron.split(' ');
|
||||
if (parts.length !== 5) return 'custom';
|
||||
if (parts.length < 5) return 'custom';
|
||||
|
||||
const [min, hr, day, month, dow] = parts;
|
||||
|
||||
@@ -137,15 +137,23 @@
|
||||
onchange(newValue);
|
||||
}
|
||||
|
||||
// Validate cron expression (supports 5-field and 6-field with seconds)
|
||||
// Validate cron expression
|
||||
function isValidCron(cron: string): boolean {
|
||||
const parts = cron.trim().split(/\s+/);
|
||||
if (parts.length !== 5 && parts.length !== 6) return false;
|
||||
if (parts.length !== 5) return false;
|
||||
|
||||
const [min, hr, day, month, dow] = parts;
|
||||
|
||||
// Basic pattern validation (number, *, */n, range, list)
|
||||
const cronFieldPattern = /^(\*|(\*\/\d+)|\d+(-\d+)?(,\d+(-\d+)?)*)$/;
|
||||
|
||||
return parts.every((part) => cronFieldPattern.test(part));
|
||||
return (
|
||||
cronFieldPattern.test(min) &&
|
||||
cronFieldPattern.test(hr) &&
|
||||
cronFieldPattern.test(day) &&
|
||||
cronFieldPattern.test(month) &&
|
||||
cronFieldPattern.test(dow)
|
||||
);
|
||||
}
|
||||
|
||||
// Human-readable description using cronstrue
|
||||
|
||||
@@ -329,40 +329,18 @@
|
||||
onExpandChange?.(key, nowExpanded);
|
||||
}
|
||||
|
||||
// Sort persistence
|
||||
const SORT_STORAGE_KEY = `dockhand-${gridId}-sort`;
|
||||
let sortInitialized = false;
|
||||
|
||||
// Restore saved sort on mount
|
||||
onMount(() => {
|
||||
if (!onSortChange) return;
|
||||
try {
|
||||
const saved = localStorage.getItem(SORT_STORAGE_KEY);
|
||||
if (saved) {
|
||||
const parsed = JSON.parse(saved) as DataGridSortState;
|
||||
if (parsed.field && parsed.direction) {
|
||||
onSortChange(parsed);
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
sortInitialized = true;
|
||||
});
|
||||
|
||||
// Persist sort state whenever it changes (after init)
|
||||
$effect(() => {
|
||||
if (!sortInitialized || !sortState) return;
|
||||
try { localStorage.setItem(SORT_STORAGE_KEY, JSON.stringify(sortState)); } catch {}
|
||||
});
|
||||
|
||||
// Sort helpers
|
||||
function toggleSort(field: string) {
|
||||
if (!onSortChange) return;
|
||||
|
||||
const newState: DataGridSortState = sortState?.field === field
|
||||
? { field, direction: sortState.direction === 'asc' ? 'desc' : 'asc' }
|
||||
: { field, direction: 'asc' };
|
||||
|
||||
onSortChange(newState);
|
||||
if (sortState?.field === field) {
|
||||
onSortChange({
|
||||
field,
|
||||
direction: sortState.direction === 'asc' ? 'desc' : 'asc'
|
||||
});
|
||||
} else {
|
||||
onSortChange({ field, direction: 'asc' });
|
||||
}
|
||||
}
|
||||
|
||||
// Virtual scroll state
|
||||
|
||||
@@ -10,7 +10,7 @@ export const containerColumns: ColumnConfig[] = [
|
||||
{ id: 'uptime', label: 'Uptime', sortable: true, sortField: 'uptime', width: 80, minWidth: 60 },
|
||||
{ id: 'restartCount', label: 'Restarts', width: 70, minWidth: 50 },
|
||||
{ id: 'cpu', label: 'CPU', sortable: true, sortField: 'cpu', width: 50, minWidth: 40, align: 'right' },
|
||||
{ id: 'memory', label: 'Memory', sortable: true, sortField: 'memory', width: 95, minWidth: 70, align: 'right' },
|
||||
{ id: 'memory', label: 'Memory', sortable: true, sortField: 'memory', width: 60, minWidth: 50, align: 'right' },
|
||||
{ id: 'networkIO', label: 'Net I/O', width: 85, minWidth: 70, align: 'right' },
|
||||
{ id: 'diskIO', label: 'Disk I/O', width: 85, minWidth: 70, align: 'right' },
|
||||
{ id: 'ip', label: 'IP', sortable: true, sortField: 'ip', width: 100, minWidth: 80 },
|
||||
|
||||
@@ -1,75 +1,4 @@
|
||||
[
|
||||
{
|
||||
"version": "1.0.27",
|
||||
"comingSoon": false,
|
||||
"date": "2026-04-26",
|
||||
"changes": [
|
||||
{ "type": "feature", "text": "network graph visualization on networks page (#894, @Penlane)" },
|
||||
{ "type": "feature", "text": "customizable compose template for new stacks in settings (#632, @oratory)" },
|
||||
{ "type": "feature", "text": "Microsoft Teams notifications via Power Automate Workflows (#355, @slokhorst)" },
|
||||
{ "type": "feature", "text": "container label controls: dockhand.update, dockhand.hidden, dockhand.notify (#6, #53, #94, #215)" },
|
||||
{ "type": "feature", "text": "configurable label filter matching mode (any/all) for environment dashboard (#607)" },
|
||||
{ "type": "feature", "text": "log search filter mode to hide non-matching lines (#916)" },
|
||||
{ "type": "feature", "text": "inline terminal on logs page with resizable split layout (#900)" },
|
||||
{ "type": "fix", "text": "disable Telegram link preview in notifications (#910, @deenle)" },
|
||||
{ "type": "fix", "text": "cron editor rejects 6-field expressions with seconds (#839, @GiulioSavini)" },
|
||||
{ "type": "fix", "text": "mirror Dockhand's ExtraHosts into scanner and self-update containers (#836, @YewFence)" },
|
||||
{ "type": "fix", "text": "duplicate volume binds during container recreate (#765, @itsDNNS)" },
|
||||
{ "type": "fix", "text": "log timestamp formatting not applied on main logs page (#882)" },
|
||||
{ "type": "fix", "text": "uploaded files now inherit container user ownership (#732, @ivanjx)" },
|
||||
{ "type": "fix", "text": "extraneous backslash in Telegram notification environment name (#955)" },
|
||||
{ "type": "fix", "text": "collapse ports into ranges only if 3 or more consecutive ports" },
|
||||
{ "type": "fix", "text": "git operations auto-merge system CAs with custom cert (#967)" }
|
||||
],
|
||||
"imageTag": "fnsys/dockhand:v1.0.27"
|
||||
},
|
||||
{
|
||||
"version": "1.0.26",
|
||||
"date": "2026-04-19",
|
||||
"changes": [
|
||||
{ "type": "feature", "text": "persist sort order across page navigation for all data grids (#861, #912)" },
|
||||
{ "type": "feature", "text": "show git repository URL and branch in git stack edit modal (#856)" },
|
||||
{ "type": "feature", "text": "show memory limit alongside usage in containers and stacks views (#893)" },
|
||||
{ "type": "feature", "text": "option to delete associated volumes when removing a stack (#655)" },
|
||||
{ "type": "feature", "text": "collapse consecutive port mappings into ranges in container list (#821)" },
|
||||
{ "type": "fix", "text": "bearer token authentication fails with enterprise license active" },
|
||||
{ "type": "fix", "text": "clicking stack name toggles stats accordion instead of just opening editor (#628)" },
|
||||
{ "type": "fix", "text": "scheduled image prune notifications missing environment name (#770)" },
|
||||
{ "type": "fix", "text": "Gotify, ntfy, Pushover, and webhook notifications missing environment name (#943)" },
|
||||
{ "type": "fix", "text": "MFA code field not recognized by Bitwarden and other password managers (#566)" }
|
||||
],
|
||||
"imageTag": "fnsys/dockhand:v1.0.26"
|
||||
},
|
||||
{
|
||||
"version": "1.0.25",
|
||||
"date": "2026-04-18",
|
||||
"comingSoon": false,
|
||||
"changes": [
|
||||
{ "type": "feature", "text": "API token authentication — Bearer tokens for CI/CD pipelines and scripts" },
|
||||
{ "type": "feature", "text": "Telegram topic support — send notifications to supergroup topics (#855)" },
|
||||
{ "type": "fix", "text": "allow removing healthcheck, ports, and honor startAfterUpdate=false during container edit (#892)" },
|
||||
{ "type": "fix", "text": "validate stack names and prevent broken DB entries on invalid input (#876)" },
|
||||
{ "type": "fix", "text": "use per-environment timezone for schedule execution log timestamps (#882)" },
|
||||
{ "type": "fix", "text": "\"Pull image before update\" and \"Start after update\" settings ignored (#909)" },
|
||||
{ "type": "fix", "text": "image prune timeout on hawser-standard when pruning many images (#905)" },
|
||||
{ "type": "fix", "text": "bump Docker Compose to 5.1.3" },
|
||||
{ "type": "fix", "text": "mask secret environment variables in container inspect modal (#924)" },
|
||||
{ "type": "fix", "text": "viewer role can toggle, delete, and run schedules (#923)" },
|
||||
{ "type": "fix", "text": "settings show defaults instead of saved values after login until page refresh (#921)" },
|
||||
{ "type": "fix", "text": "settings toggle notifications show wrong state (#931)" },
|
||||
{ "type": "fix", "text": "stack memory tooltip shows inflated total on multi-container stacks (#936)" }
|
||||
],
|
||||
"imageTag": "fnsys/dockhand:v1.0.25"
|
||||
},
|
||||
{
|
||||
"version": "1.0.24",
|
||||
"date": "2026-04-03",
|
||||
"changes": [
|
||||
{ "type": "fix", "text": "browsing HTTP registries fails with SSL error (#868)" },
|
||||
{ "type": "fix", "text": "git stack deploy options (build, re-pull, force redeploy) not persisted in edit dialog" }
|
||||
],
|
||||
"imageTag": "fnsys/dockhand:v1.0.24"
|
||||
},
|
||||
{
|
||||
"version": "1.0.23",
|
||||
"date": "2026-04-03",
|
||||
|
||||
@@ -1,274 +0,0 @@
|
||||
/**
|
||||
* API Token Management
|
||||
*
|
||||
* Provides Bearer token authentication for CI/CD pipelines and scripts.
|
||||
* Tokens use `dh_` prefix, Argon2id hashing, and prefix-based lookup.
|
||||
*
|
||||
* Performance: An in-memory cache (SHA-256 key, 60s TTL) avoids running
|
||||
* Argon2id on every request. First request: ~100ms. Subsequent: ~0ms.
|
||||
*/
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import { db, eq, and } from '$lib/server/db/drizzle';
|
||||
import { hashPassword, verifyPassword, type AuthenticatedUser } from './auth';
|
||||
import { secureRandomBytes } from './crypto-fallback';
|
||||
import { getUserRoles, userHasAdminRole, type Permissions } from './db';
|
||||
import { isEnterprise } from './license';
|
||||
import { tokenCache, ensureCleanupInterval, invalidateTokenCacheForUser, clearTokenCache } from './token-cache';
|
||||
|
||||
// Re-export cache functions so existing consumers don't need to change imports
|
||||
export { invalidateTokenCacheForUser, clearTokenCache } from './token-cache';
|
||||
|
||||
// Dynamic schema import (same pattern as db.ts)
|
||||
let apiTokensTable: any;
|
||||
|
||||
async function getApiTokensTable() {
|
||||
if (apiTokensTable) return apiTokensTable;
|
||||
const isPostgres = !!(process.env.DATABASE_URL && (
|
||||
process.env.DATABASE_URL.startsWith('postgres://') ||
|
||||
process.env.DATABASE_URL.startsWith('postgresql://')
|
||||
));
|
||||
const schema = isPostgres
|
||||
? await import('./db/schema/pg-schema.js')
|
||||
: await import('./db/schema/index.js');
|
||||
apiTokensTable = schema.apiTokens;
|
||||
return apiTokensTable;
|
||||
}
|
||||
|
||||
// Token format: dh_ + 32 bytes base64url = dh_ + 43 chars
|
||||
const TOKEN_PREFIX = 'dh_';
|
||||
const TOKEN_BYTES = 32;
|
||||
const PREFIX_LENGTH = 8; // chars after dh_ stored for identification
|
||||
const MAX_TOKEN_LENGTH = 200;
|
||||
const CACHE_TTL = 60_000; // 60 seconds
|
||||
|
||||
function cacheKey(rawToken: string): string {
|
||||
return createHash('sha256').update(rawToken).digest('hex');
|
||||
}
|
||||
|
||||
// Pre-computed dummy hash for timing protection on invalid prefixes
|
||||
let dummyHash: string | null = null;
|
||||
|
||||
async function getDummyHash(): Promise<string> {
|
||||
if (!dummyHash) {
|
||||
dummyHash = await hashPassword('dh_dummy_token_for_timing_protection');
|
||||
}
|
||||
return dummyHash;
|
||||
}
|
||||
|
||||
// Initialize dummy hash on import (fire and forget)
|
||||
void getDummyHash();
|
||||
|
||||
/**
|
||||
* Generate a new API token.
|
||||
* Returns the plaintext token (shown once) and the database record.
|
||||
*/
|
||||
export async function generateApiToken(
|
||||
userId: number,
|
||||
name: string,
|
||||
expiresAt?: string | null
|
||||
): Promise<{ token: string; id: number; tokenPrefix: string }> {
|
||||
const table = await getApiTokensTable();
|
||||
|
||||
// Generate random token
|
||||
const randomBytes = secureRandomBytes(TOKEN_BYTES);
|
||||
const rawToken = TOKEN_PREFIX + randomBytes.toString('base64url');
|
||||
const tokenPrefix = rawToken.substring(TOKEN_PREFIX.length, TOKEN_PREFIX.length + PREFIX_LENGTH);
|
||||
|
||||
// Hash for storage
|
||||
const tokenHash = await hashPassword(rawToken);
|
||||
|
||||
const result = await db.insert(table).values({
|
||||
userId,
|
||||
name,
|
||||
tokenHash,
|
||||
tokenPrefix,
|
||||
expiresAt: expiresAt || null
|
||||
}).returning();
|
||||
|
||||
return {
|
||||
token: rawToken,
|
||||
id: result[0].id,
|
||||
tokenPrefix
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a Bearer token and return the associated user.
|
||||
* Uses cache to avoid Argon2id on every request.
|
||||
*/
|
||||
export async function validateApiToken(rawToken: string): Promise<AuthenticatedUser | null> {
|
||||
// Input validation
|
||||
if (!rawToken || rawToken.length > MAX_TOKEN_LENGTH || !rawToken.startsWith(TOKEN_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check cache first
|
||||
ensureCleanupInterval();
|
||||
const key = cacheKey(rawToken);
|
||||
const cached = tokenCache.get(key);
|
||||
if (cached && cached.expiresAt > Date.now()) {
|
||||
return cached.user;
|
||||
}
|
||||
|
||||
const table = await getApiTokensTable();
|
||||
|
||||
// Extract prefix for lookup
|
||||
const prefix = rawToken.substring(TOKEN_PREFIX.length, TOKEN_PREFIX.length + PREFIX_LENGTH);
|
||||
|
||||
// Find tokens with matching prefix (deleted tokens are gone, no isActive filter needed)
|
||||
const candidates = await db
|
||||
.select()
|
||||
.from(table)
|
||||
.where(eq(table.tokenPrefix, prefix));
|
||||
|
||||
if (candidates.length === 0) {
|
||||
// Timing protection: run Argon2id anyway
|
||||
await verifyPassword(rawToken, await getDummyHash());
|
||||
return null;
|
||||
}
|
||||
|
||||
// Verify against each candidate (usually just one)
|
||||
for (const candidate of candidates) {
|
||||
const valid = await verifyPassword(rawToken, candidate.tokenHash);
|
||||
if (!valid) continue;
|
||||
|
||||
// Check expiration AFTER hash verification to avoid timing oracle
|
||||
if (candidate.expiresAt && new Date(candidate.expiresAt) < new Date()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Build AuthenticatedUser from the token's user
|
||||
const user = await buildUserFromToken(candidate);
|
||||
if (!user) continue;
|
||||
|
||||
// Update lastUsed (fire and forget — non-critical audit field)
|
||||
void db.update(table)
|
||||
.set({ lastUsed: new Date().toISOString() })
|
||||
.where(eq(table.id, candidate.id))
|
||||
.catch((err) => {
|
||||
if (typeof process !== 'undefined' && process.env.DB_VERBOSE_LOGGING === 'true') {
|
||||
console.debug('[api-tokens] lastUsed update failed:', err?.message);
|
||||
}
|
||||
});
|
||||
|
||||
// Cache the result — cap TTL at token expiry time if sooner
|
||||
let cacheTtl = CACHE_TTL;
|
||||
if (candidate.expiresAt) {
|
||||
const timeUntilExpiry = new Date(candidate.expiresAt).getTime() - Date.now();
|
||||
if (timeUntilExpiry < cacheTtl) {
|
||||
cacheTtl = Math.max(0, timeUntilExpiry);
|
||||
}
|
||||
}
|
||||
tokenCache.set(key, { user, expiresAt: Date.now() + cacheTtl });
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an AuthenticatedUser from a token's database record.
|
||||
*/
|
||||
async function buildUserFromToken(tokenRecord: any): Promise<AuthenticatedUser | null> {
|
||||
// Import getUserWithoutPassword dynamically to avoid circular deps
|
||||
// This avoids keeping passwordHash in memory unnecessarily
|
||||
const { getUserWithoutPassword } = await import('./db');
|
||||
|
||||
const dbUser = await getUserWithoutPassword(tokenRecord.userId);
|
||||
if (!dbUser || !dbUser.isActive) return null;
|
||||
|
||||
const enterprise = await isEnterprise();
|
||||
let isAdmin = false;
|
||||
let permissions: Permissions;
|
||||
|
||||
if (!enterprise) {
|
||||
// Free edition: everyone is effectively admin
|
||||
isAdmin = true;
|
||||
const { getRoleByName } = await import('./db');
|
||||
const adminRole = await getRoleByName('Admin');
|
||||
permissions = adminRole?.permissions ?? {} as Permissions;
|
||||
} else {
|
||||
isAdmin = await userHasAdminRole(dbUser.id);
|
||||
const userRoleAssignments = await getUserRoles(dbUser.id);
|
||||
// Merge permissions from all roles
|
||||
permissions = {} as Permissions;
|
||||
for (const assignment of userRoleAssignments) {
|
||||
if (!assignment.role) continue;
|
||||
const rolePerms = typeof assignment.role.permissions === 'string'
|
||||
? JSON.parse(assignment.role.permissions)
|
||||
: assignment.role.permissions;
|
||||
if (!rolePerms) continue;
|
||||
for (const [key, actions] of Object.entries(rolePerms)) {
|
||||
if (!permissions[key as keyof Permissions]) {
|
||||
permissions[key as keyof Permissions] = [];
|
||||
}
|
||||
for (const action of actions as string[]) {
|
||||
if (!permissions[key as keyof Permissions].includes(action)) {
|
||||
permissions[key as keyof Permissions].push(action);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Determine provider from authProvider field
|
||||
let provider: 'local' | 'ldap' | 'oidc' = 'local';
|
||||
if (dbUser.authProvider?.startsWith('ldap')) provider = 'ldap';
|
||||
else if (dbUser.authProvider?.startsWith('oidc')) provider = 'oidc';
|
||||
|
||||
return {
|
||||
id: dbUser.id,
|
||||
username: dbUser.username,
|
||||
email: dbUser.email ?? undefined,
|
||||
displayName: dbUser.displayName ?? undefined,
|
||||
avatar: dbUser.avatar ?? undefined,
|
||||
isAdmin,
|
||||
provider,
|
||||
permissions
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* List all tokens for a user (no hashes returned).
|
||||
*/
|
||||
export async function listUserTokens(userId: number) {
|
||||
const table = await getApiTokensTable();
|
||||
return db
|
||||
.select({
|
||||
id: table.id,
|
||||
name: table.name,
|
||||
tokenPrefix: table.tokenPrefix,
|
||||
lastUsed: table.lastUsed,
|
||||
expiresAt: table.expiresAt,
|
||||
createdAt: table.createdAt
|
||||
})
|
||||
.from(table)
|
||||
.where(eq(table.userId, userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke (delete) a token. Owner or admin can revoke.
|
||||
*/
|
||||
export async function revokeApiToken(tokenId: number, requestingUserId: number, isAdmin: boolean): Promise<boolean> {
|
||||
const table = await getApiTokensTable();
|
||||
|
||||
// Find the token
|
||||
const [token] = await db.select().from(table).where(eq(table.id, tokenId));
|
||||
if (!token) return false;
|
||||
|
||||
// Check ownership or admin
|
||||
if (token.userId !== requestingUserId && !isAdmin) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Hard-delete
|
||||
await db.delete(table).where(eq(table.id, tokenId));
|
||||
|
||||
// Clear cache — we can't map prefix to SHA-256 cache keys, so clear all
|
||||
clearTokenCache();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import type { RequestEvent } from '@sveltejs/kit';
|
||||
import { isEnterprise } from './license';
|
||||
import { logAuditEvent, type AuditAction, type AuditEntityType, type AuditLogCreateData } from './db';
|
||||
import { authorize } from './authorize';
|
||||
import { getRequestContext } from './request-context';
|
||||
|
||||
export interface AuditContext {
|
||||
userId?: number | null;
|
||||
@@ -22,8 +21,7 @@ export interface AuditContext {
|
||||
* Extract audit context from a request event
|
||||
*/
|
||||
export async function getAuditContext(event: RequestEvent): Promise<AuditContext> {
|
||||
const ctx = getRequestContext();
|
||||
const user = ctx?.user ?? (await authorize(event.cookies)).user;
|
||||
const auth = await authorize(event.cookies);
|
||||
|
||||
// Get IP address from various headers (proxied requests)
|
||||
const forwardedFor = event.request.headers.get('x-forwarded-for');
|
||||
@@ -42,8 +40,8 @@ export async function getAuditContext(event: RequestEvent): Promise<AuditContext
|
||||
const userAgent = event.request.headers.get('user-agent') || null;
|
||||
|
||||
return {
|
||||
userId: user?.id ?? null,
|
||||
username: user?.username ?? 'anonymous',
|
||||
userId: auth.user?.id ?? null,
|
||||
username: auth.user?.username ?? 'anonymous',
|
||||
ipAddress,
|
||||
userAgent
|
||||
};
|
||||
|
||||
@@ -44,7 +44,6 @@ import {
|
||||
import { Client as LdapClient } from 'ldapts';
|
||||
import { isEnterprise } from './license';
|
||||
import { secureRandomBytes } from './crypto-fallback';
|
||||
import { invalidateTokenCacheForUser } from './token-cache';
|
||||
|
||||
// Session cookie name
|
||||
const SESSION_COOKIE_NAME = 'dockhand_session';
|
||||
@@ -223,7 +222,7 @@ function setSessionCookie(cookies: Cookies, sessionId: string, maxAge: number, r
|
||||
path: '/',
|
||||
httpOnly: true, // Prevents XSS attacks from reading cookie
|
||||
secure: isSecureContext(request), // Protocol-aware: checks x-forwarded-proto or NODE_ENV
|
||||
sameSite: 'lax', // Lax required for OIDC/SSO cross-site redirects
|
||||
sameSite: 'strict', // CSRF protection
|
||||
maxAge: maxAge // Session timeout in seconds
|
||||
});
|
||||
}
|
||||
@@ -736,9 +735,6 @@ async function tryLdapAuth(
|
||||
}
|
||||
}
|
||||
|
||||
// Clear cached token permissions after role sync
|
||||
invalidateTokenCacheForUser(user.id);
|
||||
|
||||
if (!user.isActive) {
|
||||
return { success: false, error: 'Account is disabled' };
|
||||
}
|
||||
@@ -1453,9 +1449,6 @@ export async function handleOidcCallback(
|
||||
}
|
||||
}
|
||||
|
||||
// Clear cached token permissions after role sync
|
||||
invalidateTokenCacheForUser(user.id);
|
||||
|
||||
if (!user.isActive) {
|
||||
return { success: false, error: 'Account is disabled' };
|
||||
}
|
||||
|
||||
@@ -40,7 +40,6 @@ import type { Permissions } from './db';
|
||||
import { getUserAccessibleEnvironments, userCanAccessEnvironment, userHasAdminRole } from './db';
|
||||
import { validateSession, isAuthEnabled, checkPermission, type AuthenticatedUser } from './auth';
|
||||
import { isEnterprise } from './license';
|
||||
import { getRequestContext } from './request-context';
|
||||
|
||||
export interface AuthorizationContext {
|
||||
/** Whether authentication is enabled globally */
|
||||
@@ -114,10 +113,7 @@ export interface AuthorizationContext {
|
||||
export async function authorize(cookies: Cookies): Promise<AuthorizationContext> {
|
||||
const authEnabled = await isAuthEnabled();
|
||||
const enterprise = await isEnterprise();
|
||||
|
||||
// Try request context first (set by hook — handles both cookie and Bearer)
|
||||
const reqCtx = getRequestContext();
|
||||
const user = reqCtx?.user ?? (authEnabled ? await validateSession(cookies) : null);
|
||||
const user = authEnabled ? await validateSession(cookies) : null;
|
||||
|
||||
// Determine admin status:
|
||||
// - Free edition: all authenticated users are effectively admins (full access)
|
||||
@@ -159,8 +155,8 @@ export async function authorize(cookies: Cookies): Promise<AuthorizationContext>
|
||||
// Must be authenticated
|
||||
if (!user) return false;
|
||||
|
||||
// Admins can access all environments (use fresh isAdmin, not cached user.isAdmin)
|
||||
if (isAdmin) return true;
|
||||
// Admins can access all environments
|
||||
if (user.isAdmin) return true;
|
||||
|
||||
// In free edition, all authenticated users have full access
|
||||
if (!enterprise) return true;
|
||||
@@ -176,8 +172,8 @@ export async function authorize(cookies: Cookies): Promise<AuthorizationContext>
|
||||
// Must be authenticated
|
||||
if (!user) return [];
|
||||
|
||||
// Admins can access all environments (use fresh isAdmin, not cached user.isAdmin)
|
||||
if (isAdmin) return null;
|
||||
// Admins can access all environments
|
||||
if (user.isAdmin) return null;
|
||||
|
||||
// In free edition, all authenticated users have full access
|
||||
if (!enterprise) return null;
|
||||
@@ -193,8 +189,8 @@ export async function authorize(cookies: Cookies): Promise<AuthorizationContext>
|
||||
// Must be authenticated
|
||||
if (!user) return false;
|
||||
|
||||
// Admins can always manage users (use fresh isAdmin, not cached user.isAdmin)
|
||||
if (isAdmin) return true;
|
||||
// Admins can always manage users
|
||||
if (user.isAdmin) return true;
|
||||
|
||||
// In free edition, all authenticated users have full access
|
||||
if (!enterprise) return true;
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
/**
|
||||
* Dockhand Container Label Controls
|
||||
*
|
||||
* Docker container labels that control Dockhand behavior:
|
||||
* - dockhand.update=false — Skip this container during auto-updates and batch updates
|
||||
* - dockhand.hidden=true — Hide this container from the Dockhand UI
|
||||
* - dockhand.notify=false — Suppress notifications for this container's events
|
||||
*
|
||||
* All label values are case-insensitive and accept: true/yes/1 and false/no/0.
|
||||
* The opt-out model means labels override DB settings (label wins).
|
||||
*/
|
||||
|
||||
/** Recognized Dockhand label keys */
|
||||
export const DOCKHAND_LABELS = {
|
||||
UPDATE: 'dockhand.update',
|
||||
HIDDEN: 'dockhand.hidden',
|
||||
NOTIFY: 'dockhand.notify',
|
||||
} as const;
|
||||
|
||||
const TRUTHY_VALUES = new Set(['true', 'yes', '1']);
|
||||
const FALSY_VALUES = new Set(['false', 'no', '0']);
|
||||
|
||||
/**
|
||||
* Parse a label value as a boolean.
|
||||
* Returns true for: true, TRUE, yes, YES, 1
|
||||
* Returns false for: false, FALSE, no, NO, 0
|
||||
* Returns undefined for missing or unrecognized values.
|
||||
*/
|
||||
function parseLabelBool(value: string | undefined | null): boolean | undefined {
|
||||
if (value == null) return undefined;
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (TRUTHY_VALUES.has(normalized)) return true;
|
||||
if (FALSY_VALUES.has(normalized)) return false;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a label value from a Docker labels object.
|
||||
*/
|
||||
function getLabel(labels: Record<string, string> | undefined | null, key: string): string | undefined {
|
||||
if (!labels) return undefined;
|
||||
return labels[key];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a container should be skipped during auto-updates.
|
||||
* Returns true if dockhand.update is explicitly set to false/no/0.
|
||||
* Default (no label): allow updates (opt-out model).
|
||||
*/
|
||||
export function isUpdateDisabledByLabel(labels: Record<string, string> | undefined | null): boolean {
|
||||
const value = parseLabelBool(getLabel(labels, DOCKHAND_LABELS.UPDATE));
|
||||
return value === false; // explicitly disabled
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a container should be hidden from the UI.
|
||||
* Returns true if dockhand.hidden is explicitly set to true/yes/1.
|
||||
* Default (no label): visible (opt-out model).
|
||||
*/
|
||||
export function isHiddenByLabel(labels: Record<string, string> | undefined | null): boolean {
|
||||
const value = parseLabelBool(getLabel(labels, DOCKHAND_LABELS.HIDDEN));
|
||||
return value === true; // explicitly hidden
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if notifications should be suppressed for this container.
|
||||
* Returns true if dockhand.notify is explicitly set to false/no/0.
|
||||
* Default (no label): send notifications (opt-out model).
|
||||
*/
|
||||
export function isNotifyDisabledByLabel(labels: Record<string, string> | undefined | null): boolean {
|
||||
const value = parseLabelBool(getLabel(labels, DOCKHAND_LABELS.NOTIFY));
|
||||
return value === false; // explicitly disabled
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract all Dockhand label states from a container's labels.
|
||||
* Useful for including in API responses so the frontend knows about label overrides.
|
||||
*/
|
||||
export function getDockhandLabels(labels: Record<string, string> | undefined | null): {
|
||||
updateDisabled: boolean;
|
||||
hidden: boolean;
|
||||
notifyDisabled: boolean;
|
||||
} {
|
||||
return {
|
||||
updateDisabled: isUpdateDisabledByLabel(labels),
|
||||
hidden: isHiddenByLabel(labels),
|
||||
notifyDisabled: isNotifyDisabledByLabel(labels),
|
||||
};
|
||||
}
|
||||
+7
-112
@@ -78,7 +78,6 @@ import {
|
||||
|
||||
import type { AllGridPreferences, GridId, GridColumnPreferences } from '$lib/types';
|
||||
import { encrypt, decrypt } from './encryption.js';
|
||||
import { parseEnvInterpolation } from './env-interpolation';
|
||||
|
||||
// Re-export for backwards compatibility
|
||||
export { db, isPostgres, isSqlite };
|
||||
@@ -1186,37 +1185,6 @@ export async function getUser(id: number): Promise<UserData | null> {
|
||||
return results[0] as UserData || null;
|
||||
}
|
||||
|
||||
export interface SafeUserData {
|
||||
id: number;
|
||||
username: string;
|
||||
email: string | null;
|
||||
displayName: string | null;
|
||||
avatar: string | null;
|
||||
authProvider: string | null;
|
||||
mfaEnabled: boolean;
|
||||
isActive: boolean;
|
||||
lastLogin: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export async function getUserWithoutPassword(id: number): Promise<SafeUserData | null> {
|
||||
const results = await db.select({
|
||||
id: users.id,
|
||||
username: users.username,
|
||||
email: users.email,
|
||||
displayName: users.displayName,
|
||||
avatar: users.avatar,
|
||||
authProvider: users.authProvider,
|
||||
mfaEnabled: users.mfaEnabled,
|
||||
isActive: users.isActive,
|
||||
lastLogin: users.lastLogin,
|
||||
createdAt: users.createdAt,
|
||||
updatedAt: users.updatedAt
|
||||
}).from(users).where(eq(users.id, id));
|
||||
return results[0] as SafeUserData || null;
|
||||
}
|
||||
|
||||
export async function hasAdminUser(): Promise<boolean> {
|
||||
// Check if any user has the Admin role assigned
|
||||
const adminRole = await db.select().from(roles).where(eq(roles.name, 'Admin')).limit(1);
|
||||
@@ -2067,7 +2035,6 @@ export async function getGitStacksByRepositoryId(repositoryId: number): Promise<
|
||||
}
|
||||
|
||||
export async function deleteGitRepository(id: number): Promise<boolean> {
|
||||
console.log(`[GitStack] Deleting git repository id=${id} (will cascade-delete git_stacks, set null on stack_sources FKs)`);
|
||||
await db.delete(gitRepositories).where(eq(gitRepositories.id, id));
|
||||
return true;
|
||||
}
|
||||
@@ -2124,9 +2091,6 @@ export async function getGitStacks(environmentId?: number): Promise<GitStackWith
|
||||
autoUpdateCron: gitStacks.autoUpdateCron,
|
||||
webhookEnabled: gitStacks.webhookEnabled,
|
||||
webhookSecret: gitStacks.webhookSecret,
|
||||
buildOnDeploy: gitStacks.buildOnDeploy,
|
||||
repullImages: gitStacks.repullImages,
|
||||
forceRedeploy: gitStacks.forceRedeploy,
|
||||
lastSync: gitStacks.lastSync,
|
||||
lastCommit: gitStacks.lastCommit,
|
||||
syncStatus: gitStacks.syncStatus,
|
||||
@@ -2155,9 +2119,6 @@ export async function getGitStacks(environmentId?: number): Promise<GitStackWith
|
||||
autoUpdateCron: gitStacks.autoUpdateCron,
|
||||
webhookEnabled: gitStacks.webhookEnabled,
|
||||
webhookSecret: gitStacks.webhookSecret,
|
||||
buildOnDeploy: gitStacks.buildOnDeploy,
|
||||
repullImages: gitStacks.repullImages,
|
||||
forceRedeploy: gitStacks.forceRedeploy,
|
||||
lastSync: gitStacks.lastSync,
|
||||
lastCommit: gitStacks.lastCommit,
|
||||
syncStatus: gitStacks.syncStatus,
|
||||
@@ -2524,7 +2485,6 @@ export async function updateGitStack(id: number, data: Partial<GitStackData>): P
|
||||
}
|
||||
|
||||
export async function deleteGitStack(id: number): Promise<boolean> {
|
||||
console.log(`[GitStack] Deleting git_stacks row id=${id}`);
|
||||
await db.delete(gitStacks).where(eq(gitStacks.id, id));
|
||||
return true;
|
||||
}
|
||||
@@ -2784,21 +2744,11 @@ export async function upsertStackSource(data: {
|
||||
const existing = await getStackSource(data.stackName, data.environmentId);
|
||||
|
||||
if (existing) {
|
||||
const newRepoId = data.gitRepositoryId || null;
|
||||
const newStackId = data.gitStackId || null;
|
||||
const changes: string[] = [];
|
||||
if (data.sourceType !== existing.sourceType) changes.push(`sourceType: ${existing.sourceType} → ${data.sourceType}`);
|
||||
if (newRepoId !== existing.gitRepositoryId) changes.push(`gitRepoId: ${existing.gitRepositoryId} → ${newRepoId}`);
|
||||
if (newStackId !== existing.gitStackId) changes.push(`gitStackId: ${existing.gitStackId} → ${newStackId}`);
|
||||
if (changes.length > 0) {
|
||||
console.log(`[GitStack] Updating stack_sources "${data.stackName}" env=${data.environmentId}: ${changes.join(', ')}`);
|
||||
}
|
||||
|
||||
await db.update(stackSources)
|
||||
.set({
|
||||
sourceType: data.sourceType,
|
||||
gitRepositoryId: newRepoId,
|
||||
gitStackId: newStackId,
|
||||
gitRepositoryId: data.gitRepositoryId || null,
|
||||
gitStackId: data.gitStackId || null,
|
||||
composePath: data.composePath ?? null,
|
||||
envPath: data.envPath ?? null,
|
||||
updatedAt: new Date().toISOString()
|
||||
@@ -2806,7 +2756,6 @@ export async function upsertStackSource(data: {
|
||||
.where(eq(stackSources.id, existing.id));
|
||||
return getStackSource(data.stackName, data.environmentId) as Promise<StackSourceData>;
|
||||
} else {
|
||||
console.log(`[GitStack] Creating stack_sources "${data.stackName}" env=${data.environmentId} type=${data.sourceType} repoId=${data.gitRepositoryId || null} stackId=${data.gitStackId || null}`);
|
||||
await db.insert(stackSources).values({
|
||||
stackName: data.stackName,
|
||||
environmentId: data.environmentId ?? null,
|
||||
@@ -2840,7 +2789,6 @@ export async function updateStackSource(
|
||||
}
|
||||
|
||||
export async function deleteStackSource(stackName: string, environmentId?: number | null): Promise<boolean> {
|
||||
console.log(`[GitStack] Deleting stack_sources "${stackName}" env=${environmentId}`);
|
||||
// Delete matching record (either with specific envId or NULL)
|
||||
await db.delete(stackSources)
|
||||
.where(and(
|
||||
@@ -3092,7 +3040,7 @@ export type AuditAction =
|
||||
export type AuditEntityType =
|
||||
| 'container' | 'image' | 'stack' | 'volume' | 'network'
|
||||
| 'user' | 'role' | 'settings' | 'environment' | 'registry' | 'git_repository' | 'git_credential'
|
||||
| 'config_set' | 'notification' | 'oidc_provider' | 'ldap_config' | 'git_stack' | 'api_token';
|
||||
| 'config_set' | 'notification' | 'oidc_provider' | 'ldap_config' | 'git_stack';
|
||||
|
||||
export interface AuditLogData {
|
||||
id: number;
|
||||
@@ -3208,16 +3156,14 @@ export async function getAuditLogs(filters: AuditLogFilters = {}): Promise<Audit
|
||||
// Labels filter - find environments with matching labels first
|
||||
let labelFilteredEnvIds: number[] | undefined;
|
||||
if (filters.labels && filters.labels.length > 0) {
|
||||
const labelFilterMode = await getSetting('label_filter_mode') ?? 'any';
|
||||
// Get environments that have ANY of the specified labels
|
||||
const allEnvs = await db.select({ id: environments.id, labels: environments.labels }).from(environments);
|
||||
labelFilteredEnvIds = allEnvs
|
||||
.filter(env => {
|
||||
if (!env.labels) return false;
|
||||
try {
|
||||
const envLabels = JSON.parse(env.labels) as string[];
|
||||
return labelFilterMode === 'all'
|
||||
? filters.labels!.every(label => envLabels.includes(label))
|
||||
: filters.labels!.some(label => envLabels.includes(label));
|
||||
return filters.labels!.some(label => envLabels.includes(label));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
@@ -3425,16 +3371,14 @@ export async function getContainerEvents(filters: ContainerEventFilters = {}): P
|
||||
// Labels filter - find environments with matching labels first
|
||||
let labelFilteredEnvIds: number[] | undefined;
|
||||
if (filters.labels && filters.labels.length > 0) {
|
||||
const labelFilterMode = await getSetting('label_filter_mode') ?? 'any';
|
||||
// Get environments that have ANY of the specified labels
|
||||
const allEnvs = await db.select({ id: environments.id, labels: environments.labels }).from(environments);
|
||||
labelFilteredEnvIds = allEnvs
|
||||
.filter(env => {
|
||||
if (!env.labels) return false;
|
||||
try {
|
||||
const envLabels = JSON.parse(env.labels) as string[];
|
||||
return labelFilterMode === 'all'
|
||||
? filters.labels!.every(label => envLabels.includes(label))
|
||||
: filters.labels!.some(label => envLabels.includes(label));
|
||||
return filters.labels!.some(label => envLabels.includes(label));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
@@ -4636,55 +4580,6 @@ export async function setStackEnvVars(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the set of secret key names for a stack.
|
||||
* Used to mask secret values in container inspect responses.
|
||||
*/
|
||||
export async function getSecretKeyNames(
|
||||
stackName: string,
|
||||
environmentId?: number | null
|
||||
): Promise<Set<string>> {
|
||||
const vars = await getStackEnvVars(stackName, environmentId, true);
|
||||
return new Set(vars.filter(v => v.isSecret).map(v => v.key));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the set of env var keys that should be masked in container inspect responses.
|
||||
* Handles two cases:
|
||||
* 1. Direct match: env var key == secret key in DB (e.g., DB_PASS=${DB_PASS})
|
||||
* 2. Interpolation: env var key differs from secret key (e.g., MYSQL_PASSWORD=${db_secret})
|
||||
* Detected by parsing the compose file for ${variable} references in environment: sections.
|
||||
*
|
||||
* @param composeContent - Optional compose file content. If provided, interpolation
|
||||
* references are parsed to detect secrets injected under different key names.
|
||||
*/
|
||||
export async function getSecretKeysToMask(
|
||||
stackName: string,
|
||||
environmentId?: number | null,
|
||||
composeContent?: string | null
|
||||
): Promise<Set<string>> {
|
||||
const vars = await getStackEnvVars(stackName, environmentId, true);
|
||||
const secretKeyNames = new Set(vars.filter(v => v.isSecret).map(v => v.key));
|
||||
|
||||
if (secretKeyNames.size === 0) return secretKeyNames;
|
||||
|
||||
// If we have compose content, parse interpolation references to find
|
||||
// container env keys that map to secret interpolation variables.
|
||||
// e.g., "MYSQL_PASSWORD=${db_secret}" → if db_secret is a secret, mask MYSQL_PASSWORD too.
|
||||
if (composeContent) {
|
||||
const interpolated = parseEnvInterpolation(composeContent);
|
||||
for (const [containerKey, varName] of interpolated) {
|
||||
if (secretKeyNames.has(varName)) {
|
||||
secretKeyNames.add(containerKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return secretKeyNames;
|
||||
}
|
||||
|
||||
export { parseEnvInterpolation } from './env-interpolation';
|
||||
|
||||
/**
|
||||
* Get count of environment variables for a stack.
|
||||
* @param stackName - Name of the stack
|
||||
|
||||
@@ -335,8 +335,7 @@ const REQUIRED_TABLES = [
|
||||
'audit_logs',
|
||||
'container_events',
|
||||
'schedule_executions',
|
||||
'user_preferences',
|
||||
'api_tokens'
|
||||
'user_preferences'
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -769,7 +768,7 @@ async function seedDatabase(): Promise<void> {
|
||||
license: ['manage'],
|
||||
audit_logs: ['view'],
|
||||
activity: ['view'],
|
||||
schedules: ['view', 'edit', 'run']
|
||||
schedules: ['view']
|
||||
});
|
||||
|
||||
const operatorPermissions = JSON.stringify({
|
||||
@@ -788,7 +787,7 @@ async function seedDatabase(): Promise<void> {
|
||||
license: [],
|
||||
audit_logs: [],
|
||||
activity: ['view'],
|
||||
schedules: ['view', 'edit', 'run']
|
||||
schedules: ['view']
|
||||
});
|
||||
|
||||
const viewerPermissions = JSON.stringify({
|
||||
@@ -899,7 +898,6 @@ export const userPreferences = schemaProxy.userPreferences;
|
||||
export const scheduleExecutions = schemaProxy.scheduleExecutions;
|
||||
export const stackEnvironmentVariables = schemaProxy.stackEnvironmentVariables;
|
||||
export const pendingContainerUpdates = schemaProxy.pendingContainerUpdates;
|
||||
export const apiTokens = schemaProxy.apiTokens;
|
||||
|
||||
// Re-export types from SQLite schema (they're compatible with PostgreSQL)
|
||||
export type {
|
||||
@@ -958,9 +956,7 @@ export type {
|
||||
StackEnvironmentVariable,
|
||||
NewStackEnvironmentVariable,
|
||||
PendingContainerUpdate,
|
||||
NewPendingContainerUpdate,
|
||||
ApiToken,
|
||||
NewApiToken
|
||||
NewPendingContainerUpdate
|
||||
} from './schema/index.js';
|
||||
|
||||
export { eq, and, or, desc, asc, like, sql, inArray, isNull, isNotNull } from 'drizzle-orm';
|
||||
|
||||
@@ -467,25 +467,6 @@ export const pendingContainerUpdates = sqliteTable('pending_container_updates',
|
||||
envContainerUnique: unique().on(table.environmentId, table.containerId)
|
||||
}));
|
||||
|
||||
// =============================================================================
|
||||
// API TOKENS TABLE
|
||||
// =============================================================================
|
||||
|
||||
export const apiTokens = sqliteTable('api_tokens', {
|
||||
id: integer('id').primaryKey({ autoIncrement: true }),
|
||||
userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
|
||||
name: text('name').notNull(),
|
||||
tokenHash: text('token_hash').notNull().unique(),
|
||||
tokenPrefix: text('token_prefix').notNull(),
|
||||
lastUsed: text('last_used'),
|
||||
expiresAt: text('expires_at'),
|
||||
createdAt: text('created_at').default(sql`CURRENT_TIMESTAMP`),
|
||||
updatedAt: text('updated_at').default(sql`CURRENT_TIMESTAMP`)
|
||||
}, (table) => ({
|
||||
userIdIdx: index('api_tokens_user_id_idx').on(table.userId),
|
||||
tokenPrefixIdx: index('api_tokens_token_prefix_idx').on(table.tokenPrefix)
|
||||
}));
|
||||
|
||||
// =============================================================================
|
||||
// USER PREFERENCES TABLE (unified key-value store)
|
||||
// =============================================================================
|
||||
@@ -589,6 +570,3 @@ export type NewStackEnvironmentVariable = typeof stackEnvironmentVariables.$infe
|
||||
|
||||
export type PendingContainerUpdate = typeof pendingContainerUpdates.$inferSelect;
|
||||
export type NewPendingContainerUpdate = typeof pendingContainerUpdates.$inferInsert;
|
||||
|
||||
export type ApiToken = typeof apiTokens.$inferSelect;
|
||||
export type NewApiToken = typeof apiTokens.$inferInsert;
|
||||
|
||||
@@ -470,25 +470,6 @@ export const pendingContainerUpdates = pgTable('pending_container_updates', {
|
||||
envContainerUnique: unique().on(table.environmentId, table.containerId)
|
||||
}));
|
||||
|
||||
// =============================================================================
|
||||
// API TOKENS TABLE
|
||||
// =============================================================================
|
||||
|
||||
export const apiTokens = pgTable('api_tokens', {
|
||||
id: serial('id').primaryKey(),
|
||||
userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
|
||||
name: text('name').notNull(),
|
||||
tokenHash: text('token_hash').notNull().unique(),
|
||||
tokenPrefix: text('token_prefix').notNull(),
|
||||
lastUsed: timestamp('last_used', { mode: 'string' }),
|
||||
expiresAt: timestamp('expires_at', { mode: 'string' }),
|
||||
createdAt: timestamp('created_at', { mode: 'string' }).defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { mode: 'string' }).defaultNow()
|
||||
}, (table) => ({
|
||||
userIdIdx: index('api_tokens_user_id_idx').on(table.userId),
|
||||
tokenPrefixIdx: index('api_tokens_token_prefix_idx').on(table.tokenPrefix)
|
||||
}));
|
||||
|
||||
// =============================================================================
|
||||
// USER PREFERENCES TABLE (unified key-value store)
|
||||
// =============================================================================
|
||||
|
||||
+37
-55
@@ -14,7 +14,6 @@ import * as tls from 'node:tls';
|
||||
import { createHash } from 'node:crypto';
|
||||
import type { Environment } from './db';
|
||||
import { getStackEnvVarsAsRecord } from './db';
|
||||
import { getAdditionalVolumeBinds } from './mount-dedupe';
|
||||
import { isSystemContainer } from './scheduler/tasks/update-utils';
|
||||
import { deepDiff } from '../utils/diff.js';
|
||||
|
||||
@@ -416,8 +415,7 @@ export function httpsAgentRequest(
|
||||
if (!streaming) {
|
||||
const isComposeOperation = path === '/_hawser/compose';
|
||||
const composeTimeoutMs = parseInt(process.env.COMPOSE_TIMEOUT || '900') * 1000;
|
||||
const isPrune = path.endsWith('/prune');
|
||||
reqOptions.timeout = isComposeOperation ? composeTimeoutMs : isPrune ? 300000 : 30000;
|
||||
reqOptions.timeout = isComposeOperation ? composeTimeoutMs : 30000;
|
||||
}
|
||||
|
||||
// Honor AbortSignal from caller (e.g., AbortSignal.timeout(5000) for ping)
|
||||
@@ -886,7 +884,7 @@ export async function dockerFetch(
|
||||
body,
|
||||
headers,
|
||||
streaming || false,
|
||||
(streaming || path === '/_hawser/compose' || path.endsWith('/prune')) ? 300000 : 30000, // 5 min for streaming/compose/prune, 30s for normal
|
||||
(streaming || path === '/_hawser/compose') ? 300000 : 30000, // 5 min for streaming/compose, 30s for normal
|
||||
isBinary,
|
||||
fetchOptions.signal ?? undefined
|
||||
);
|
||||
@@ -962,8 +960,7 @@ export async function dockerFetch(
|
||||
if (!streaming && !finalOptions.signal) {
|
||||
const isComposeOperation = path === '/_hawser/compose';
|
||||
const composeTimeoutMs = parseInt(process.env.COMPOSE_TIMEOUT || '900') * 1000;
|
||||
const isPrune = path.endsWith('/prune');
|
||||
finalOptions.signal = AbortSignal.timeout(isComposeOperation ? composeTimeoutMs : isPrune ? 300000 : 30000);
|
||||
finalOptions.signal = AbortSignal.timeout(isComposeOperation ? composeTimeoutMs : 30000);
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -1228,9 +1225,9 @@ export interface DeviceRequest {
|
||||
export interface CreateContainerOptions {
|
||||
name: string;
|
||||
image: string;
|
||||
ports?: { [key: string]: { HostIp?: string; HostPort: string } } | null;
|
||||
ports?: { [key: string]: { HostIp?: string; HostPort: string } };
|
||||
volumes?: { [key: string]: {} };
|
||||
volumeBinds?: string[] | null;
|
||||
volumeBinds?: string[];
|
||||
env?: string[];
|
||||
labels?: { [key: string]: string };
|
||||
cmd?: string[];
|
||||
@@ -1250,7 +1247,7 @@ export interface CreateContainerOptions {
|
||||
networkGwPriority?: number;
|
||||
user?: string | null;
|
||||
privileged?: boolean;
|
||||
healthcheck?: HealthcheckConfig | null;
|
||||
healthcheck?: HealthcheckConfig;
|
||||
memory?: number;
|
||||
memoryReservation?: number;
|
||||
memorySwap?: number;
|
||||
@@ -1341,10 +1338,7 @@ export async function createContainer(options: CreateContainerOptions, envId?: n
|
||||
containerConfig.User = options.user ?? '';
|
||||
}
|
||||
|
||||
if (options.healthcheck === null) {
|
||||
// Explicitly disable healthcheck (user cleared it)
|
||||
containerConfig.Healthcheck = { Test: ["NONE"] };
|
||||
} else if (options.healthcheck) {
|
||||
if (options.healthcheck) {
|
||||
containerConfig.Healthcheck = {};
|
||||
if (options.healthcheck.test && options.healthcheck.test.length > 0) {
|
||||
containerConfig.Healthcheck.Test = options.healthcheck.test;
|
||||
@@ -1363,11 +1357,7 @@ export async function createContainer(options: CreateContainerOptions, envId?: n
|
||||
}
|
||||
}
|
||||
|
||||
if (options.ports === null) {
|
||||
// Explicitly clear ports (user removed all mappings)
|
||||
containerConfig.ExposedPorts = {};
|
||||
containerConfig.HostConfig.PortBindings = {};
|
||||
} else if (options.ports) {
|
||||
if (options.ports) {
|
||||
containerConfig.ExposedPorts = {};
|
||||
containerConfig.HostConfig.PortBindings = {};
|
||||
|
||||
@@ -1377,10 +1367,7 @@ export async function createContainer(options: CreateContainerOptions, envId?: n
|
||||
}
|
||||
}
|
||||
|
||||
if (options.volumeBinds === null) {
|
||||
// Explicitly clear volume binds (user removed all)
|
||||
containerConfig.HostConfig.Binds = [];
|
||||
} else if (options.volumeBinds && options.volumeBinds.length > 0) {
|
||||
if (options.volumeBinds && options.volumeBinds.length > 0) {
|
||||
containerConfig.HostConfig.Binds = options.volumeBinds;
|
||||
}
|
||||
|
||||
@@ -1918,7 +1905,20 @@ export async function recreateContainerFromInspect(
|
||||
}
|
||||
}
|
||||
|
||||
const additionalBinds = getAdditionalVolumeBinds(hostConfig, inspectData.Mounts || []);
|
||||
// Preserve anonymous volumes from Mounts not in HostConfig.Binds
|
||||
const existingBinds = new Set((hostConfig.Binds || []).map((b: string) => {
|
||||
const parts = b.split(':');
|
||||
return parts.length >= 2 ? parts[1] : parts[0];
|
||||
}));
|
||||
const mounts = inspectData.Mounts || [];
|
||||
const additionalBinds: string[] = [];
|
||||
for (const mount of mounts) {
|
||||
if (mount.Type === 'volume' && mount.Name && mount.Destination) {
|
||||
if (!existingBinds.has(mount.Destination)) {
|
||||
additionalBinds.push(`${mount.Name}:${mount.Destination}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (additionalBinds.length > 0) {
|
||||
createConfig.HostConfig = {
|
||||
...hostConfig,
|
||||
@@ -2393,7 +2393,7 @@ export async function updateContainer(id: string, options: Partial<CreateContain
|
||||
}
|
||||
|
||||
// 5. Start if needed
|
||||
if (startAfterUpdate) {
|
||||
if (startAfterUpdate || wasRunning) {
|
||||
try {
|
||||
await newContainer.start();
|
||||
} catch (startError) {
|
||||
@@ -2625,9 +2625,7 @@ function parseImageReference(imageName: string): { registry: string; repo: strin
|
||||
* 'ghcr.io' -> { host: 'ghcr.io', path: '', fullRegistry: 'ghcr.io' }
|
||||
* 'registry.example.com:5000/myorg' -> { host: 'registry.example.com:5000', path: '/myorg', fullRegistry: 'registry.example.com:5000/myorg' }
|
||||
*/
|
||||
export function parseRegistryUrl(url: string): { host: string; path: string; fullRegistry: string; protocol: string } {
|
||||
// Detect protocol (default to https)
|
||||
const protocol = url.startsWith('http://') ? 'http' : 'https';
|
||||
export function parseRegistryUrl(url: string): { host: string; path: string; fullRegistry: string } {
|
||||
// Remove protocol
|
||||
const withoutProtocol = url.replace(/^https?:\/\//, '');
|
||||
// Remove trailing slash
|
||||
@@ -2635,11 +2633,11 @@ export function parseRegistryUrl(url: string): { host: string; path: string; ful
|
||||
// Split on first slash (after port if present)
|
||||
const slashIndex = trimmed.indexOf('/');
|
||||
if (slashIndex === -1) {
|
||||
return { host: trimmed, path: '', fullRegistry: trimmed, protocol };
|
||||
return { host: trimmed, path: '', fullRegistry: trimmed };
|
||||
}
|
||||
const host = trimmed.substring(0, slashIndex);
|
||||
const path = trimmed.substring(slashIndex); // includes leading /
|
||||
return { host, path, fullRegistry: trimmed, protocol };
|
||||
return { host, path, fullRegistry: trimmed };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2824,7 +2822,7 @@ export async function getRegistryAuthHeader(
|
||||
try {
|
||||
// Parse URL to extract host (V2 API is always at the host root)
|
||||
const parsed = parseRegistryUrl(registryUrl);
|
||||
const apiBaseUrl = `${parsed.protocol}://${parsed.host}`;
|
||||
const apiBaseUrl = `https://${parsed.host}`;
|
||||
|
||||
// Step 1: Challenge request to /v2/ (always at registry root, not under org path)
|
||||
const challengeResponse = await fetch(`${apiBaseUrl}/v2/`, {
|
||||
@@ -2933,7 +2931,7 @@ export async function getRegistryAuth(
|
||||
const parsed = parseRegistryUrl(registry.url);
|
||||
|
||||
// V2 API endpoints are always at the registry host root
|
||||
const baseUrl = `${parsed.protocol}://${parsed.host}`;
|
||||
const baseUrl = `https://${parsed.host}`;
|
||||
|
||||
// Get auth header using proper token flow
|
||||
const credentials = registry.username && registry.password
|
||||
@@ -3844,25 +3842,19 @@ export async function getContainerTop(id: string, envId?: number | null): Promis
|
||||
export async function execInContainer(
|
||||
containerId: string,
|
||||
cmd: string[],
|
||||
envId?: number | null,
|
||||
user?: string | null
|
||||
envId?: number | null
|
||||
): Promise<string> {
|
||||
const execBody: any = {
|
||||
Cmd: cmd,
|
||||
AttachStdout: true,
|
||||
AttachStderr: true,
|
||||
Tty: false
|
||||
};
|
||||
|
||||
if (user) {
|
||||
execBody.User = user;
|
||||
}
|
||||
|
||||
// Create exec instance
|
||||
const execCreate = await dockerJsonRequest<{ Id: string }>(
|
||||
`/containers/${containerId}/exec`,
|
||||
{
|
||||
method: 'POST',
|
||||
body: JSON.stringify(execBody)
|
||||
body: JSON.stringify({
|
||||
Cmd: cmd,
|
||||
AttachStdout: true,
|
||||
AttachStderr: true,
|
||||
Tty: false
|
||||
})
|
||||
},
|
||||
envId
|
||||
);
|
||||
@@ -3958,7 +3950,6 @@ export async function runContainer(options: {
|
||||
cmd: string[];
|
||||
binds?: string[];
|
||||
env?: string[];
|
||||
extraHosts?: string[];
|
||||
name?: string;
|
||||
envId?: number | null;
|
||||
}): Promise<{ stdout: string; stderr: string }> {
|
||||
@@ -3980,10 +3971,6 @@ export async function runContainer(options: {
|
||||
}
|
||||
};
|
||||
|
||||
if (options.extraHosts && options.extraHosts.length > 0) {
|
||||
containerConfig.HostConfig.ExtraHosts = options.extraHosts;
|
||||
}
|
||||
|
||||
const createResult = await dockerJsonRequest<{ Id: string }>(
|
||||
`/containers/create?name=${encodeURIComponent(containerName)}`,
|
||||
{
|
||||
@@ -4043,7 +4030,6 @@ export async function runContainerWithStreaming(options: {
|
||||
cmd: string[];
|
||||
binds?: string[];
|
||||
env?: string[];
|
||||
extraHosts?: string[];
|
||||
name?: string;
|
||||
user?: string;
|
||||
envId?: number | null;
|
||||
@@ -4071,10 +4057,6 @@ export async function runContainerWithStreaming(options: {
|
||||
}
|
||||
};
|
||||
|
||||
if (options.extraHosts && options.extraHosts.length > 0) {
|
||||
containerConfig.HostConfig.ExtraHosts = options.extraHosts;
|
||||
}
|
||||
|
||||
// Set user if specified (needed for rootless Docker socket access)
|
||||
if (options.user) {
|
||||
containerConfig.User = options.user;
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
/**
|
||||
* Parse compose YAML to extract environment variable interpolation mappings.
|
||||
* Returns pairs of [containerEnvKey, interpolationVariable].
|
||||
*
|
||||
* Handles patterns:
|
||||
* - VAR=${ref}
|
||||
* - VAR=${ref:-default}
|
||||
* - VAR=${ref:+alt}
|
||||
* - VAR=${ref?error}
|
||||
*
|
||||
* Only extracts from `environment:` sections (list format: `- KEY=value`).
|
||||
*/
|
||||
export function parseEnvInterpolation(composeContent: string): Array<[string, string]> {
|
||||
const results: Array<[string, string]> = [];
|
||||
|
||||
// Step 1: Find lines matching `- ENV_KEY=...${...}...`
|
||||
const linePattern = /^\s*-\s*([A-Za-z_][A-Za-z0-9_]*)=(.*)/gm;
|
||||
let lineMatch;
|
||||
while ((lineMatch = linePattern.exec(composeContent)) !== null) {
|
||||
const containerKey = lineMatch[1];
|
||||
const valueStr = lineMatch[2];
|
||||
|
||||
// Step 2: Extract all ${VAR} references from the value
|
||||
const varPattern = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?:[:\-\+\?][^}]*)?\}/g;
|
||||
let varMatch;
|
||||
while ((varMatch = varPattern.exec(valueStr)) !== null) {
|
||||
const varName = varMatch[1];
|
||||
// Only add if names differ — same-name case handled by direct key matching
|
||||
if (containerKey !== varName) {
|
||||
results.push([containerKey, varName]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
+2
-68
@@ -16,70 +16,6 @@ import {
|
||||
} from './db';
|
||||
import { deployStack, getStackDir } from './stacks';
|
||||
|
||||
const MERGED_CA_BUNDLE_PATH = '/tmp/dockhand-merged-ca-bundle.crt';
|
||||
let mergedCaBundleReady = false;
|
||||
|
||||
/**
|
||||
* Create a merged CA bundle combining system CAs with the custom cert from
|
||||
* NODE_EXTRA_CA_CERTS. GIT_SSL_CAINFO replaces the default CA store, so without
|
||||
* merging, public CAs (GitHub, GitLab) break.
|
||||
*/
|
||||
function getMergedCaBundlePath(): string {
|
||||
if (mergedCaBundleReady && existsSync(MERGED_CA_BUNDLE_PATH)) {
|
||||
console.log(`[Git] Using cached merged CA bundle: ${MERGED_CA_BUNDLE_PATH}`);
|
||||
return MERGED_CA_BUNDLE_PATH;
|
||||
}
|
||||
|
||||
const customCertPath = process.env.NODE_EXTRA_CA_CERTS!;
|
||||
console.log(`[Git] NODE_EXTRA_CA_CERTS set to: ${customCertPath}`);
|
||||
|
||||
const systemCaPaths = [
|
||||
process.env.SSL_CERT_FILE,
|
||||
'/etc/ssl/certs/ca-certificates.crt',
|
||||
'/etc/pki/tls/certs/ca-bundle.crt',
|
||||
'/etc/ssl/cert.pem'
|
||||
];
|
||||
|
||||
let systemCaContent = '';
|
||||
let systemCaSource = '';
|
||||
for (const caPath of systemCaPaths) {
|
||||
if (caPath && existsSync(caPath)) {
|
||||
try {
|
||||
systemCaContent = readFileSync(caPath, 'utf-8');
|
||||
systemCaSource = caPath;
|
||||
console.log(`[Git] Found system CA bundle: ${caPath} (${systemCaContent.split('-----BEGIN CERTIFICATE-----').length - 1} certs)`);
|
||||
break;
|
||||
} catch (err) {
|
||||
console.log(`[Git] Failed to read system CA bundle ${caPath}: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!systemCaSource) {
|
||||
console.log(`[Git] No system CA bundle found, using custom cert only: ${customCertPath}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const customCaContent = readFileSync(customCertPath, 'utf-8');
|
||||
const customCertCount = customCaContent.split('-----BEGIN CERTIFICATE-----').length - 1;
|
||||
console.log(`[Git] Custom CA file contains ${customCertCount} cert(s)`);
|
||||
|
||||
const merged = systemCaContent
|
||||
? systemCaContent.trimEnd() + '\n' + customCaContent.trimEnd() + '\n'
|
||||
: customCaContent;
|
||||
writeFileSync(MERGED_CA_BUNDLE_PATH, merged);
|
||||
mergedCaBundleReady = true;
|
||||
|
||||
const totalCerts = merged.split('-----BEGIN CERTIFICATE-----').length - 1;
|
||||
console.log(`[Git] Created merged CA bundle: ${MERGED_CA_BUNDLE_PATH} (${totalCerts} total certs — system from ${systemCaSource || 'none'} + custom from ${customCertPath})`);
|
||||
} catch (err) {
|
||||
console.warn(`[Git] Failed to create merged CA bundle, falling back to custom cert only: ${customCertPath}`, err);
|
||||
return customCertPath;
|
||||
}
|
||||
|
||||
return MERGED_CA_BUNDLE_PATH;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect stdout, stderr and exit code from a spawned process.
|
||||
*/
|
||||
@@ -217,11 +153,9 @@ async function buildGitEnv(credential: GitCredential | null): Promise<GitEnv> {
|
||||
SSH_AUTH_SOCK: ''
|
||||
};
|
||||
|
||||
// Pass custom CA certificate to git CLI (NODE_EXTRA_CA_CERTS only affects Node.js).
|
||||
// GIT_SSL_CAINFO replaces the default CA store, so we merge system CAs with the
|
||||
// custom cert so both self-signed repos and public repos (GitHub etc.) work (#967).
|
||||
// Pass custom CA certificate to git CLI (NODE_EXTRA_CA_CERTS only affects Node.js)
|
||||
if (process.env.NODE_EXTRA_CA_CERTS) {
|
||||
env.GIT_SSL_CAINFO = getMergedCaBundlePath();
|
||||
env.GIT_SSL_CAINFO = process.env.NODE_EXTRA_CA_CERTS;
|
||||
}
|
||||
|
||||
// Ensure current UID is resolvable for SSH/git operations
|
||||
|
||||
+17
-20
@@ -9,7 +9,6 @@ import { db, hawserTokens, environments, eq, and } from './db/drizzle.js';
|
||||
import { logContainerEvent, type ContainerEventAction } from './db.js';
|
||||
import { containerEventEmitter } from './event-collector.js';
|
||||
import { sendEnvironmentNotification } from './notifications.js';
|
||||
import { isNotifyDisabledByLabel } from './container-labels.js';
|
||||
import { pushMetric } from './metrics-store.js';
|
||||
import { secureGetRandomValues, secureRandomUUID } from './crypto-fallback.js';
|
||||
import { hashPassword, verifyPassword } from './auth.js';
|
||||
@@ -192,26 +191,24 @@ export async function handleEdgeContainerEvent(
|
||||
// Broadcast to SSE clients
|
||||
containerEventEmitter.emit('event', savedEvent);
|
||||
|
||||
// Check dockhand.notify label before sending notification
|
||||
// Docker includes container labels in actorAttributes
|
||||
if (!isNotifyDisabledByLabel(event.actorAttributes)) {
|
||||
const actionLabel = event.action.charAt(0).toUpperCase() + event.action.slice(1);
|
||||
const containerLabel = event.containerName || event.containerId.substring(0, 12);
|
||||
const notificationType =
|
||||
event.action === 'die' || event.action === 'kill' || event.action === 'oom'
|
||||
? 'error'
|
||||
: event.action === 'stop'
|
||||
? 'warning'
|
||||
: event.action === 'start'
|
||||
? 'success'
|
||||
: 'info';
|
||||
// Prepare notification
|
||||
const actionLabel = event.action.charAt(0).toUpperCase() + event.action.slice(1);
|
||||
const containerLabel = event.containerName || event.containerId.substring(0, 12);
|
||||
const notificationType =
|
||||
event.action === 'die' || event.action === 'kill' || event.action === 'oom'
|
||||
? 'error'
|
||||
: event.action === 'stop'
|
||||
? 'warning'
|
||||
: event.action === 'start'
|
||||
? 'success'
|
||||
: 'info';
|
||||
|
||||
await sendEnvironmentNotification(environmentId, event.action as ContainerEventAction, {
|
||||
title: `Container ${actionLabel}`,
|
||||
message: `Container "${containerLabel}" ${event.action}${event.image ? ` (${event.image})` : ''}`,
|
||||
type: notificationType as 'success' | 'error' | 'warning' | 'info'
|
||||
}, event.image);
|
||||
}
|
||||
// Send notification
|
||||
await sendEnvironmentNotification(environmentId, event.action as ContainerEventAction, {
|
||||
title: `Container ${actionLabel}`,
|
||||
message: `Container "${containerLabel}" ${event.action}${event.image ? ` (${event.image})` : ''}`,
|
||||
type: notificationType as 'success' | 'error' | 'warning' | 'info'
|
||||
}, event.image);
|
||||
} catch (error) {
|
||||
const errorMsg = error instanceof Error ? error.message : String(error);
|
||||
console.error('[Hawser] Error handling container event:', errorMsg);
|
||||
|
||||
@@ -34,7 +34,6 @@ let cachedMounts: Array<{ source: string; destination: string }> | null = null;
|
||||
// Used by scanner to replicate how Dockhand connects to Docker
|
||||
let cachedOwnDockerHost: string | null = null;
|
||||
let cachedOwnNetworkMode: string | null = null;
|
||||
let cachedOwnExtraHosts: string[] | null = null;
|
||||
|
||||
/**
|
||||
* Get our own container ID
|
||||
@@ -86,11 +85,12 @@ export async function detectHostDataDir(): Promise<string | null> {
|
||||
if (process.env.HOST_DATA_DIR) {
|
||||
cachedHostDataDir = process.env.HOST_DATA_DIR;
|
||||
console.log(`[HostPath] Using HOST_DATA_DIR from environment: ${cachedHostDataDir}`);
|
||||
return cachedHostDataDir;
|
||||
}
|
||||
|
||||
const containerId = getOwnContainerId();
|
||||
if (!containerId) {
|
||||
console.warn('[HostPath] Running in Docker but could not detect container ID; ExtraHosts will not be mirrored to sidecars');
|
||||
console.warn('[HostPath] Running in Docker but could not detect container ID');
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -140,9 +140,6 @@ export async function detectHostDataDir(): Promise<string | null> {
|
||||
Config?: {
|
||||
Env?: string[];
|
||||
};
|
||||
HostConfig?: {
|
||||
ExtraHosts?: string[];
|
||||
};
|
||||
NetworkSettings?: {
|
||||
Networks?: Record<string, unknown>;
|
||||
};
|
||||
@@ -179,19 +176,6 @@ export async function detectHostDataDir(): Promise<string | null> {
|
||||
}
|
||||
}
|
||||
|
||||
cachedOwnExtraHosts = containerInfo.HostConfig?.ExtraHosts?.length
|
||||
? [...containerInfo.HostConfig.ExtraHosts]
|
||||
: null;
|
||||
if (cachedOwnExtraHosts) {
|
||||
console.log(`[HostPath] Detected own ExtraHosts: ${cachedOwnExtraHosts.join(', ')}`);
|
||||
}
|
||||
|
||||
// Explicit override wins for DATA_DIR path, but we still inspect to populate
|
||||
// mounts/network/DOCKER_HOST/ExtraHosts caches for sibling sidecars.
|
||||
if (cachedHostDataDir) {
|
||||
return cachedHostDataDir;
|
||||
}
|
||||
|
||||
// Find the mount for our DATA_DIR
|
||||
const dataMount = containerInfo.Mounts?.find(m => m.Destination === dataDir);
|
||||
|
||||
@@ -245,15 +229,6 @@ export function getOwnNetworkMode(): string | null {
|
||||
return cachedOwnNetworkMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the ExtraHosts entries configured on Dockhand itself.
|
||||
* Used to mirror host aliases into sibling sidecar containers.
|
||||
* Populated by detectHostDataDir() at startup.
|
||||
*/
|
||||
export function getOwnExtraHosts(): string[] | null {
|
||||
return cachedOwnExtraHosts ? [...cachedOwnExtraHosts] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate a container path to host path
|
||||
*
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
type HostConfigLike = {
|
||||
Binds?: string[] | null;
|
||||
Mounts?: Array<{ Target?: string | null }> | null;
|
||||
};
|
||||
|
||||
type InspectMountLike = {
|
||||
Type?: string | null;
|
||||
Name?: string | null;
|
||||
Destination?: string | null;
|
||||
};
|
||||
|
||||
/** Build extra bind strings for volume mounts missing from HostConfig. */
|
||||
export function getAdditionalVolumeBinds(
|
||||
hostConfig: HostConfigLike,
|
||||
mounts: InspectMountLike[]
|
||||
): string[] {
|
||||
const existingMountTargets = new Set((hostConfig.Binds || []).map((bind: string) => {
|
||||
const parts = bind.split(':');
|
||||
return parts.length >= 2 ? parts[1] : parts[0];
|
||||
}));
|
||||
|
||||
for (const mount of hostConfig.Mounts || []) {
|
||||
if (mount?.Target) existingMountTargets.add(mount.Target);
|
||||
}
|
||||
|
||||
const additionalBinds: string[] = [];
|
||||
for (const mount of mounts || []) {
|
||||
if (mount.Type === 'volume' && mount.Name && mount.Destination) {
|
||||
if (!existingMountTargets.has(mount.Destination)) {
|
||||
additionalBinds.push(`${mount.Name}:${mount.Destination}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return additionalBinds;
|
||||
}
|
||||
@@ -9,7 +9,17 @@ import {
|
||||
type NotificationEventType
|
||||
} from './db';
|
||||
|
||||
import { escapeTelegramMarkdown, parseTelegramUrl, buildGotifyUrl, parseWorkflowsUrl, buildWorkflowsHttpUrl } from '$lib/utils/notification-parsers';
|
||||
// Escape special characters for Telegram Markdown
|
||||
function escapeTelegramMarkdown(text: string): string {
|
||||
// Escape characters that have special meaning in Telegram Markdown
|
||||
return text
|
||||
.replace(/\\/g, '\\\\') // Escape backslashes first
|
||||
.replace(/_/g, '\\_') // Underscore (italic)
|
||||
.replace(/\*/g, '\\*') // Asterisk (bold)
|
||||
.replace(/\[/g, '\\[') // Opening bracket (link)
|
||||
.replace(/\]/g, '\\]') // Closing bracket (link)
|
||||
.replace(/`/g, '\\`'); // Backtick (code)
|
||||
}
|
||||
|
||||
/** Drain a response body to release the underlying socket/TLS connection. */
|
||||
async function drainResponse(response: Response): Promise<void> {
|
||||
@@ -134,8 +144,6 @@ async function sendToAppriseUrl(url: string, payload: NotificationPayload): Prom
|
||||
case 'json':
|
||||
case 'jsons':
|
||||
return await sendGenericWebhook(url, payload);
|
||||
case 'workflows':
|
||||
return await sendWorkflows(url, payload);
|
||||
default:
|
||||
return { success: false, error: `Unsupported Apprise protocol: ${protocol}` };
|
||||
}
|
||||
@@ -269,18 +277,19 @@ async function sendMattermost(appriseUrl: string, payload: NotificationPayload):
|
||||
|
||||
// Telegram
|
||||
async function sendTelegram(appriseUrl: string, payload: NotificationPayload): Promise<NotificationResult> {
|
||||
const parsed = parseTelegramUrl(appriseUrl);
|
||||
if (!parsed) {
|
||||
return { success: false, error: 'Invalid Telegram URL format. Expected: tgram://bot_token/chat_id or tgram://bot_token/chat_id:topic_id' };
|
||||
// tgram://bot_token/chat_id
|
||||
const match = appriseUrl.match(/^tgram:\/\/([^/]+)\/(.+)/);
|
||||
if (!match) {
|
||||
return { success: false, error: 'Invalid Telegram URL format. Expected: tgram://bot_token/chat_id' };
|
||||
}
|
||||
|
||||
const { botToken, chatId, topicId } = parsed;
|
||||
const [, botToken, chatId] = match;
|
||||
const url = `https://api.telegram.org/bot${botToken}/sendMessage`;
|
||||
|
||||
// Escape markdown special characters in title and message
|
||||
const escapedTitle = escapeTelegramMarkdown(payload.title);
|
||||
const escapedMessage = escapeTelegramMarkdown(payload.message);
|
||||
const envTag = payload.environmentName ? ` [${escapeTelegramMarkdown(payload.environmentName)}]` : '';
|
||||
const envTag = payload.environmentName ? ` \\[${escapeTelegramMarkdown(payload.environmentName)}\\]` : '';
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
@@ -289,11 +298,7 @@ async function sendTelegram(appriseUrl: string, payload: NotificationPayload): P
|
||||
body: JSON.stringify({
|
||||
chat_id: chatId,
|
||||
text: `*${escapedTitle}*${envTag}\n${escapedMessage}`,
|
||||
...(topicId ? { message_thread_id: topicId } : {}),
|
||||
parse_mode: 'Markdown',
|
||||
link_preview_options: {
|
||||
is_disabled: true
|
||||
}
|
||||
parse_mode: 'Markdown'
|
||||
})
|
||||
});
|
||||
|
||||
@@ -311,19 +316,27 @@ async function sendTelegram(appriseUrl: string, payload: NotificationPayload): P
|
||||
|
||||
// Gotify
|
||||
async function sendGotify(appriseUrl: string, payload: NotificationPayload): Promise<NotificationResult> {
|
||||
const url = buildGotifyUrl(appriseUrl);
|
||||
if (!url) {
|
||||
// gotify://hostname/token or gotifys://hostname/token
|
||||
// gotify://hostname/subpath/token (subpath support)
|
||||
const match = appriseUrl.match(/^gotifys?:\/\/([^/]+)\/(.+)/);
|
||||
if (!match) {
|
||||
return { success: false, error: 'Invalid Gotify URL format. Expected: gotify://hostname/token' };
|
||||
}
|
||||
|
||||
const titleWithEnv = payload.environmentName ? `${payload.title} [${payload.environmentName}]` : payload.title;
|
||||
const [, hostname, pathPart] = match;
|
||||
const protocol = appriseUrl.startsWith('gotifys') ? 'https' : 'http';
|
||||
// Token is always the last path segment; anything before it is a subpath
|
||||
const lastSlash = pathPart.lastIndexOf('/');
|
||||
const subpath = lastSlash >= 0 ? pathPart.substring(0, lastSlash) : '';
|
||||
const token = lastSlash >= 0 ? pathPart.substring(lastSlash + 1) : pathPart;
|
||||
const url = `${protocol}://${hostname}${subpath ? '/' + subpath : ''}/message?token=${token}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
title: titleWithEnv,
|
||||
title: payload.title,
|
||||
message: payload.message,
|
||||
priority: payload.type === 'error' ? 8 : payload.type === 'warning' ? 5 : 2
|
||||
})
|
||||
@@ -379,9 +392,8 @@ async function sendNtfy(appriseUrl: string, payload: NotificationPayload): Promi
|
||||
url = `https://ntfy.sh/${path}`;
|
||||
}
|
||||
|
||||
const titleWithEnv = payload.environmentName ? `${payload.title} [${payload.environmentName}]` : payload.title;
|
||||
const headers: Record<string, string> = {
|
||||
'Title': titleWithEnv,
|
||||
'Title': payload.title,
|
||||
'Priority': payload.type === 'error' ? '5' : payload.type === 'warning' ? '4' : '3',
|
||||
'Tags': payload.type || 'info'
|
||||
};
|
||||
@@ -418,7 +430,6 @@ async function sendPushover(appriseUrl: string, payload: NotificationPayload): P
|
||||
|
||||
const [, userKey, apiToken] = match;
|
||||
const url = 'https://api.pushover.net/1/messages.json';
|
||||
const titleWithEnv = payload.environmentName ? `${payload.title} [${payload.environmentName}]` : payload.title;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
@@ -427,7 +438,7 @@ async function sendPushover(appriseUrl: string, payload: NotificationPayload): P
|
||||
body: JSON.stringify({
|
||||
token: apiToken,
|
||||
user: userKey,
|
||||
title: titleWithEnv,
|
||||
title: payload.title,
|
||||
message: payload.message,
|
||||
priority: payload.type === 'error' ? 1 : 0
|
||||
})
|
||||
@@ -457,7 +468,6 @@ async function sendGenericWebhook(appriseUrl: string, payload: NotificationPaylo
|
||||
title: payload.title,
|
||||
message: payload.message,
|
||||
type: payload.type || 'info',
|
||||
environment: payload.environmentName || null,
|
||||
timestamp: new Date().toISOString()
|
||||
})
|
||||
});
|
||||
@@ -472,59 +482,6 @@ async function sendGenericWebhook(appriseUrl: string, payload: NotificationPaylo
|
||||
return { success: false, error: `Webhook connection failed: ${error instanceof Error ? error.message : String(error)}` };
|
||||
}
|
||||
}
|
||||
// Microsoft Power Automate Workflows, for e.g. Microsoft Teams
|
||||
async function sendWorkflows(appriseUrl: string, payload: NotificationPayload): Promise<NotificationResult> {
|
||||
const parsed = parseWorkflowsUrl(appriseUrl);
|
||||
if (!parsed) {
|
||||
return { success: false, error: 'Invalid Workflows URL format. Expected: workflows://hostname/workflow/signature' };
|
||||
}
|
||||
|
||||
const url = buildWorkflowsHttpUrl(parsed.hostname, parsed.workflow, parsed.signature);
|
||||
const titleWithEnv = payload.environmentName ? `${payload.title} [${payload.environmentName}]` : payload.title;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
type: 'message',
|
||||
attachments: [
|
||||
{
|
||||
contentType: 'application/vnd.microsoft.card.adaptive',
|
||||
content: {
|
||||
$schema: 'https://adaptivecards.io/schemas/adaptive-card.json',
|
||||
type: 'AdaptiveCard',
|
||||
version: '1.2',
|
||||
body: [
|
||||
{
|
||||
type: 'TextBlock',
|
||||
style: 'heading',
|
||||
wrap: true,
|
||||
text: titleWithEnv
|
||||
},
|
||||
{
|
||||
type: 'TextBlock',
|
||||
style: 'default',
|
||||
wrap: true,
|
||||
text: payload.message
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text().catch(() => '');
|
||||
return { success: false, error: `Workflows error ${response.status}: ${text || response.statusText}` };
|
||||
}
|
||||
await drainResponse(response);
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: `Workflows connection failed: ${error instanceof Error ? error.message : String(error)}` };
|
||||
}
|
||||
}
|
||||
|
||||
// Send notification to all enabled channels
|
||||
export async function sendNotification(payload: NotificationPayload): Promise<{ success: boolean; results: { name: string; success: boolean }[] }> {
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
/**
|
||||
* Request-scoped context using AsyncLocalStorage.
|
||||
*
|
||||
* The hook sets the authenticated user (from cookie or Bearer token)
|
||||
* and wraps resolve() in requestContext.run(). Downstream code like
|
||||
* authorize() reads the pre-resolved user from here instead of
|
||||
* re-validating the session.
|
||||
*/
|
||||
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
import type { AuthenticatedUser } from './auth';
|
||||
|
||||
export interface RequestContext {
|
||||
user: AuthenticatedUser | null;
|
||||
authEnabled: boolean;
|
||||
authMethod: 'cookie' | 'bearer' | 'none';
|
||||
}
|
||||
|
||||
export const requestContext = new AsyncLocalStorage<RequestContext>();
|
||||
|
||||
export function getRequestContext(): RequestContext | undefined {
|
||||
return requestContext.getStore();
|
||||
}
|
||||
@@ -16,14 +16,7 @@ import {
|
||||
} from './docker';
|
||||
import { getEnvironment, getEnvSetting, getSetting } from './db';
|
||||
import { sendEventNotification } from './notifications';
|
||||
import {
|
||||
getHostDockerSocket,
|
||||
getHostDataDir,
|
||||
extractUidFromSocketPath,
|
||||
getOwnDockerHost,
|
||||
getOwnExtraHosts,
|
||||
getOwnNetworkMode
|
||||
} from './host-path';
|
||||
import { getHostDockerSocket, getHostDataDir, extractUidFromSocketPath, getOwnDockerHost, getOwnNetworkMode } from './host-path';
|
||||
import { resolve } from 'node:path';
|
||||
import { mkdir, chown, rm } from 'node:fs/promises';
|
||||
|
||||
@@ -632,7 +625,6 @@ async function runScannerContainerCore(
|
||||
let rootlessUid: string | undefined;
|
||||
let scannerNetworkMode: string | undefined;
|
||||
let scannerDockerHost: string | undefined;
|
||||
const scannerExtraHosts = !isHawser ? getOwnExtraHosts() ?? undefined : undefined;
|
||||
|
||||
// Check if Dockhand itself uses TCP to reach Docker (e.g., socket proxy).
|
||||
// Detected at startup from Dockhand's own container inspect data.
|
||||
@@ -644,12 +636,7 @@ async function runScannerContainerCore(
|
||||
// TCP mode: scanner uses the same DOCKER_HOST + network as Dockhand
|
||||
scannerDockerHost = ownDockerHost;
|
||||
scannerNetworkMode = getOwnNetworkMode() ?? undefined;
|
||||
console.log(
|
||||
`[Scanner] TCP mode (from container inspect) - DOCKER_HOST=${scannerDockerHost}, network=${scannerNetworkMode ?? 'default'}`
|
||||
);
|
||||
if (scannerExtraHosts?.length) {
|
||||
console.log(`[Scanner] Reusing ExtraHosts from Dockhand: ${scannerExtraHosts.join(', ')}`);
|
||||
}
|
||||
console.log(`[Scanner] TCP mode (from container inspect) - DOCKER_HOST=${scannerDockerHost}, network=${scannerNetworkMode ?? 'default'}`);
|
||||
} else if (isHawser) {
|
||||
// Hawser: scanner runs on remote host, uses remote host's standard Docker socket
|
||||
hostSocketPath = '/var/run/docker.sock';
|
||||
@@ -666,10 +653,6 @@ async function runScannerContainerCore(
|
||||
console.log(`[Scanner] Rootless Docker detected (UID ${rootlessUid})`);
|
||||
console.log(`[Scanner] Scanner will run as root inside container (maps to UID ${rootlessUid} on host via user namespace)`);
|
||||
}
|
||||
|
||||
if (scannerExtraHosts?.length) {
|
||||
console.log(`[Scanner] Reusing ExtraHosts from Dockhand: ${scannerExtraHosts.join(', ')}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Determine cache storage strategy based on environment
|
||||
@@ -739,7 +722,6 @@ async function runScannerContainerCore(
|
||||
cmd,
|
||||
binds,
|
||||
env: envVars,
|
||||
extraHosts: scannerExtraHosts,
|
||||
name: `dockhand-${scannerType}-${Date.now()}`,
|
||||
envId,
|
||||
networkMode: scannerNetworkMode,
|
||||
|
||||
@@ -38,7 +38,6 @@ import {
|
||||
import { getScannerSettings, scanImage, type ScanResult, type VulnerabilitySeverity } from '../../scanner';
|
||||
import { sendEventNotification } from '../../notifications';
|
||||
import { parseImageNameAndTag, shouldBlockUpdate, combineScanSummaries, isSystemContainer } from './update-utils';
|
||||
import { isUpdateDisabledByLabel } from '../../container-labels';
|
||||
|
||||
// =============================================================================
|
||||
// TYPES
|
||||
@@ -370,18 +369,6 @@ export async function runContainerUpdate(
|
||||
return;
|
||||
}
|
||||
|
||||
// Check dockhand.update label (label wins over DB settings)
|
||||
if (isUpdateDisabledByLabel(inspectData.Config?.Labels)) {
|
||||
log(`Skipping - dockhand.update=false label set on container`);
|
||||
await updateScheduleExecution(execution.id, {
|
||||
status: 'skipped',
|
||||
completedAt: new Date().toISOString(),
|
||||
duration: Date.now() - startTime,
|
||||
details: { reason: 'Skipped by dockhand.update=false label' }
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip digest-pinned images - they are explicitly locked to a specific version
|
||||
if (isDigestBasedImage(imageNameFromConfig)) {
|
||||
log(`Skipping ${containerName} - image pinned to specific digest`);
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
import { sendEventNotification } from '../../notifications';
|
||||
import { getScannerSettings, scanImage, type VulnerabilitySeverity } from '../../scanner';
|
||||
import { parseImageNameAndTag, shouldBlockUpdate, combineScanSummaries, isSystemContainer } from './update-utils';
|
||||
import { isUpdateDisabledByLabel } from '../../container-labels';
|
||||
import { recreateContainer } from './container-update';
|
||||
|
||||
interface UpdateInfo {
|
||||
@@ -130,12 +129,6 @@ export async function runEnvUpdateCheckJob(
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check dockhand.update label (label wins over DB settings)
|
||||
if (isUpdateDisabledByLabel(inspectData.Config?.Labels)) {
|
||||
await log(` [${container.name}] Skipping - dockhand.update=false label`);
|
||||
continue;
|
||||
}
|
||||
|
||||
checkedCount++;
|
||||
await log(` Checking: ${container.name} (${imageName})`);
|
||||
|
||||
|
||||
@@ -124,7 +124,7 @@ export async function runImagePrune(
|
||||
// Send success notification only when something was actually cleaned up
|
||||
if (imagesRemoved > 0) {
|
||||
await sendEventNotification('image_prune_success', {
|
||||
title: `Image prune completed — ${env.name}`,
|
||||
title: 'Image prune completed',
|
||||
message: `${imagesRemoved} unused images removed, ${formatBytes(spaceReclaimed)} disk space reclaimed`,
|
||||
type: 'success'
|
||||
}, envId);
|
||||
@@ -142,7 +142,7 @@ export async function runImagePrune(
|
||||
|
||||
// Send failure notification
|
||||
await sendEventNotification('image_prune_failed', {
|
||||
title: `Image prune failed — ${env.name}`,
|
||||
title: 'Image prune failed',
|
||||
message: `Failed to prune images: ${error.message}`,
|
||||
type: 'error'
|
||||
}, envId);
|
||||
|
||||
@@ -752,10 +752,9 @@ async function loginToRegistries(dockerHost?: string, logPrefix = '[Stack]', api
|
||||
}
|
||||
|
||||
try {
|
||||
// Extract registry host from URL (parseRegistryUrl handles bare hostnames like 'ghcr.io')
|
||||
const { parseRegistryUrl } = await import('./docker.js');
|
||||
const { host } = parseRegistryUrl(reg.url);
|
||||
const registryHost = host;
|
||||
// Extract registry host from URL
|
||||
const url = new URL(reg.url);
|
||||
const registryHost = url.host;
|
||||
|
||||
console.log(`${logPrefix} Logging into registry: ${registryHost}`);
|
||||
|
||||
@@ -1982,8 +1981,7 @@ export async function downStack(
|
||||
export async function removeStack(
|
||||
stackName: string,
|
||||
envId?: number | null,
|
||||
force = false,
|
||||
removeVolumes = false
|
||||
force = false
|
||||
): Promise<StackOperationResult> {
|
||||
return withStackLock(stackName, async () => {
|
||||
// Get compose file (may not exist for external stacks)
|
||||
@@ -2001,7 +1999,6 @@ export async function removeStack(
|
||||
{
|
||||
stackName,
|
||||
envId,
|
||||
removeVolumes,
|
||||
workingDir: composeResult.stackDir,
|
||||
composePath: composeResult.composePath ?? undefined,
|
||||
envPath: composeResult.envPath ?? undefined
|
||||
|
||||
@@ -24,7 +24,6 @@ import {
|
||||
type ContainerEventAction
|
||||
} from './db';
|
||||
import { sendEnvironmentNotification, sendEventNotification } from './notifications';
|
||||
import { isNotifyDisabledByLabel } from './container-labels';
|
||||
import { rssBeforeOp, rssAfterOp } from './rss-tracker';
|
||||
import { pushMetric } from './metrics-store';
|
||||
|
||||
@@ -286,28 +285,24 @@ async function handleContainerEvent(msg: GoMessage): Promise<void> {
|
||||
|
||||
// Sub-category: notification
|
||||
const notifBefore = rssBeforeOp();
|
||||
const actionLabel = action.startsWith('health_status')
|
||||
? action.includes('unhealthy') ? 'Unhealthy' : 'Healthy'
|
||||
: action.charAt(0).toUpperCase() + action.slice(1);
|
||||
const containerLabel = containerName || containerId.substring(0, 12);
|
||||
const notificationType =
|
||||
action === 'die' || action === 'kill' || action === 'oom' || action.includes('unhealthy')
|
||||
? 'error'
|
||||
: action === 'stop'
|
||||
? 'warning'
|
||||
: action === 'start' || (action.includes('healthy') && !action.includes('unhealthy'))
|
||||
? 'success'
|
||||
: 'info';
|
||||
|
||||
// Check dockhand.notify label — Docker includes container labels in event Actor.Attributes
|
||||
if (!isNotifyDisabledByLabel(event.Actor?.Attributes)) {
|
||||
const actionLabel = action.startsWith('health_status')
|
||||
? action.includes('unhealthy') ? 'Unhealthy' : 'Healthy'
|
||||
: action.charAt(0).toUpperCase() + action.slice(1);
|
||||
const containerLabel = containerName || containerId.substring(0, 12);
|
||||
const notificationType =
|
||||
action === 'die' || action === 'kill' || action === 'oom' || action.includes('unhealthy')
|
||||
? 'error'
|
||||
: action === 'stop'
|
||||
? 'warning'
|
||||
: action === 'start' || (action.includes('healthy') && !action.includes('unhealthy'))
|
||||
? 'success'
|
||||
: 'info';
|
||||
|
||||
sendEnvironmentNotification(msg.envId, action, {
|
||||
title: `Container ${actionLabel}`,
|
||||
message: `Container "${containerLabel}" ${action}${image ? ` (${image})` : ''}`,
|
||||
type: notificationType
|
||||
}, image).catch(() => {});
|
||||
}
|
||||
sendEnvironmentNotification(msg.envId, action, {
|
||||
title: `Container ${actionLabel}`,
|
||||
message: `Container "${containerLabel}" ${action}${image ? ` (${image})` : ''}`,
|
||||
type: notificationType
|
||||
}, image).catch(() => {});
|
||||
rssAfterOp('events_notif', notifBefore);
|
||||
rssAfterOp('events', before);
|
||||
}
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
/**
|
||||
* API Token Cache — LRU with TTL
|
||||
*
|
||||
* In-memory cache for validated API tokens. Without this, every Bearer
|
||||
* request would run Argon2id verification (~64MB RAM, ~100ms CPU per call).
|
||||
*
|
||||
* Cache key is SHA-256(fullToken) — safe to hold in memory (not reversible).
|
||||
* TTL is 60s by default, capped at the token's expiry time if sooner.
|
||||
*
|
||||
* Uses a bounded LRU (max 1024 entries) to cap memory usage. On overflow
|
||||
* the least-recently-used entry is evicted. Expired entries are also pruned
|
||||
* every 5 minutes.
|
||||
*
|
||||
* Separated from api-tokens.ts to avoid circular dependencies
|
||||
* (auth.ts ↔ api-tokens.ts).
|
||||
*/
|
||||
|
||||
export interface TokenCacheEntry {
|
||||
user: { id: number; [key: string]: any };
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
const MAX_CACHE_SIZE = 1024;
|
||||
|
||||
/**
|
||||
* Simple LRU cache backed by a Map.
|
||||
* Map iteration order is insertion order, so we delete-and-re-set on every
|
||||
* access to move the entry to the "newest" position. The oldest entry
|
||||
* (Map.keys().next()) is evicted when the cache exceeds MAX_CACHE_SIZE.
|
||||
*/
|
||||
class LruTokenCache {
|
||||
private map = new Map<string, TokenCacheEntry>();
|
||||
|
||||
get(key: string): TokenCacheEntry | undefined {
|
||||
const entry = this.map.get(key);
|
||||
if (!entry) return undefined;
|
||||
// Move to end (most-recently-used)
|
||||
this.map.delete(key);
|
||||
this.map.set(key, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
set(key: string, entry: TokenCacheEntry): void {
|
||||
// If key already exists, delete first so re-insert moves it to end
|
||||
if (this.map.has(key)) {
|
||||
this.map.delete(key);
|
||||
}
|
||||
this.map.set(key, entry);
|
||||
// Evict oldest if over capacity
|
||||
if (this.map.size > MAX_CACHE_SIZE) {
|
||||
const oldest = this.map.keys().next().value!;
|
||||
this.map.delete(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
delete(key: string): void {
|
||||
this.map.delete(key);
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.map.clear();
|
||||
}
|
||||
|
||||
entries(): IterableIterator<[string, TokenCacheEntry]> {
|
||||
return this.map.entries();
|
||||
}
|
||||
|
||||
get size(): number {
|
||||
return this.map.size;
|
||||
}
|
||||
}
|
||||
|
||||
export const tokenCache = new LruTokenCache();
|
||||
|
||||
/**
|
||||
* Invalidate all cached tokens for a specific user.
|
||||
* Call when user permissions change, roles are updated, or user is deleted/deactivated.
|
||||
*/
|
||||
export function invalidateTokenCacheForUser(userId: number): void {
|
||||
for (const [key, entry] of tokenCache.entries()) {
|
||||
if (entry.user.id === userId) {
|
||||
tokenCache.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the entire token cache.
|
||||
* Called on revocation, role permission edits, and license state changes.
|
||||
*/
|
||||
export function clearTokenCache(): void {
|
||||
tokenCache.clear();
|
||||
}
|
||||
|
||||
// Periodic cleanup every 5 minutes
|
||||
let cleanupInterval: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
export function ensureCleanupInterval(): void {
|
||||
if (cleanupInterval) return;
|
||||
cleanupInterval = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [key, entry] of tokenCache.entries()) {
|
||||
if (entry.expiresAt <= now) {
|
||||
tokenCache.delete(key);
|
||||
}
|
||||
}
|
||||
}, 5 * 60 * 1000);
|
||||
if (cleanupInterval.unref) cleanupInterval.unref();
|
||||
}
|
||||
@@ -5,7 +5,6 @@ export type TimeFormat = '12h' | '24h';
|
||||
export type DateFormat = 'MM/DD/YYYY' | 'DD/MM/YYYY' | 'YYYY-MM-DD' | 'DD.MM.YYYY';
|
||||
export type DownloadFormat = 'tar' | 'tar.gz';
|
||||
export type EventCollectionMode = 'stream' | 'poll';
|
||||
export type LabelFilterMode = 'any' | 'all';
|
||||
|
||||
export interface AppSettings {
|
||||
confirmDestructive: boolean;
|
||||
@@ -33,8 +32,6 @@ export interface AppSettings {
|
||||
primaryStackLocation: string | null;
|
||||
defaultGrypeImage: string;
|
||||
defaultTrivyImage: string;
|
||||
defaultComposeTemplate: string;
|
||||
labelFilterMode: LabelFilterMode;
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: AppSettings = {
|
||||
@@ -62,26 +59,7 @@ const DEFAULT_SETTINGS: AppSettings = {
|
||||
externalStackPaths: [],
|
||||
primaryStackLocation: null,
|
||||
defaultGrypeImage: 'anchore/grype:v0.110.0',
|
||||
defaultTrivyImage: 'aquasec/trivy:0.69.3',
|
||||
labelFilterMode: 'any',
|
||||
defaultComposeTemplate: `version: "3.8"
|
||||
|
||||
services:
|
||||
app:
|
||||
image: nginx:alpine
|
||||
ports:
|
||||
- "8080:80"
|
||||
environment:
|
||||
- APP_ENV=\${APP_ENV:-production}
|
||||
volumes:
|
||||
- ./html:/usr/share/nginx/html:ro
|
||||
restart: unless-stopped
|
||||
|
||||
# Add more services as needed
|
||||
# networks:
|
||||
# default:
|
||||
# driver: bridge
|
||||
`
|
||||
defaultTrivyImage: 'aquasec/trivy:0.69.3'
|
||||
};
|
||||
|
||||
// Create a writable store for app settings
|
||||
@@ -123,9 +101,7 @@ function createSettingsStore() {
|
||||
externalStackPaths: settings.externalStackPaths ?? DEFAULT_SETTINGS.externalStackPaths,
|
||||
primaryStackLocation: settings.primaryStackLocation ?? DEFAULT_SETTINGS.primaryStackLocation,
|
||||
defaultGrypeImage: settings.defaultGrypeImage ?? DEFAULT_SETTINGS.defaultGrypeImage,
|
||||
defaultTrivyImage: settings.defaultTrivyImage ?? DEFAULT_SETTINGS.defaultTrivyImage,
|
||||
defaultComposeTemplate: settings.defaultComposeTemplate ?? DEFAULT_SETTINGS.defaultComposeTemplate,
|
||||
labelFilterMode: settings.labelFilterMode ?? DEFAULT_SETTINGS.labelFilterMode
|
||||
defaultTrivyImage: settings.defaultTrivyImage ?? DEFAULT_SETTINGS.defaultTrivyImage
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
@@ -170,9 +146,7 @@ function createSettingsStore() {
|
||||
externalStackPaths: updatedSettings.externalStackPaths ?? DEFAULT_SETTINGS.externalStackPaths,
|
||||
primaryStackLocation: updatedSettings.primaryStackLocation ?? DEFAULT_SETTINGS.primaryStackLocation,
|
||||
defaultGrypeImage: updatedSettings.defaultGrypeImage ?? DEFAULT_SETTINGS.defaultGrypeImage,
|
||||
defaultTrivyImage: updatedSettings.defaultTrivyImage ?? DEFAULT_SETTINGS.defaultTrivyImage,
|
||||
defaultComposeTemplate: updatedSettings.defaultComposeTemplate ?? DEFAULT_SETTINGS.defaultComposeTemplate,
|
||||
labelFilterMode: updatedSettings.labelFilterMode ?? DEFAULT_SETTINGS.labelFilterMode
|
||||
defaultTrivyImage: updatedSettings.defaultTrivyImage ?? DEFAULT_SETTINGS.defaultTrivyImage
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -374,25 +348,8 @@ function createSettingsStore() {
|
||||
return newSettings;
|
||||
});
|
||||
},
|
||||
setDefaultComposeTemplate: (value: string) => {
|
||||
update((current) => {
|
||||
const newSettings = { ...current, defaultComposeTemplate: value };
|
||||
saveSettings({ defaultComposeTemplate: value });
|
||||
return newSettings;
|
||||
});
|
||||
},
|
||||
setLabelFilterMode: (value: LabelFilterMode) => {
|
||||
update((current) => {
|
||||
const newSettings = { ...current, labelFilterMode: value };
|
||||
saveSettings({ labelFilterMode: value });
|
||||
return newSettings;
|
||||
});
|
||||
},
|
||||
// Manual refresh from database
|
||||
refresh: () => {
|
||||
initialized = false;
|
||||
return loadSettings();
|
||||
}
|
||||
refresh: loadSettings
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
// Pure parsing/building functions for notification providers.
|
||||
// Extracted from notifications.ts so unit tests can import without pulling in DB deps.
|
||||
|
||||
// --- Telegram ---
|
||||
|
||||
// Escape special characters for Telegram legacy Markdown (parse_mode: 'Markdown')
|
||||
// Only _ * ` [ need escaping — ] and other chars are not special in legacy mode
|
||||
export function escapeTelegramMarkdown(text: string): string {
|
||||
return text
|
||||
.replace(/_/g, '\\_') // Underscore (italic)
|
||||
.replace(/\*/g, '\\*') // Asterisk (bold)
|
||||
.replace(/`/g, '\\`') // Backtick (code)
|
||||
.replace(/\[/g, '\\['); // Opening bracket (link)
|
||||
}
|
||||
|
||||
export function parseTelegramUrl(url: string): { botToken: string; chatId: string; topicId?: number } | null {
|
||||
const match = url.match(/^tgram:\/\/([^/]+)\/([^:\/]+)(?::(\d+))?$/);
|
||||
if (!match) return null;
|
||||
const [, botToken, chatId, topicIdStr] = match;
|
||||
return { botToken, chatId, topicId: topicIdStr ? parseInt(topicIdStr, 10) : undefined };
|
||||
}
|
||||
|
||||
// --- Gotify ---
|
||||
|
||||
export function buildGotifyUrl(appriseUrl: string): string | null {
|
||||
const match = appriseUrl.match(/^gotifys?:\/\/([^/]+)\/(.+)/);
|
||||
if (!match) return null;
|
||||
const [, hostname, pathPart] = match;
|
||||
const protocol = appriseUrl.startsWith('gotifys') ? 'https' : 'http';
|
||||
const lastSlash = pathPart.lastIndexOf('/');
|
||||
const subpath = lastSlash >= 0 ? pathPart.substring(0, lastSlash) : '';
|
||||
const token = lastSlash >= 0 ? pathPart.substring(lastSlash + 1) : pathPart;
|
||||
return `${protocol}://${hostname}${subpath ? '/' + subpath : ''}/message?token=${token}`;
|
||||
}
|
||||
|
||||
// --- Workflows (Microsoft Power Automate) ---
|
||||
|
||||
export function parseWorkflowsUrl(appriseUrl: string): { hostname: string; workflow: string; signature: string } | null {
|
||||
const match = appriseUrl.match(/^workflows?:\/\/([^/]+)\/(.+)\/(.+)/);
|
||||
if (!match) return null;
|
||||
const [, hostname, workflow, signature] = match;
|
||||
return { hostname, workflow, signature };
|
||||
}
|
||||
|
||||
export function buildWorkflowsHttpUrl(hostname: string, workflow: string, signature: string): string {
|
||||
return `https://${hostname}/powerautomate/automations/direct/workflows/${workflow}/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=${signature}`;
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
export interface PortMapping {
|
||||
publicPort: number;
|
||||
privatePort: number;
|
||||
display: string;
|
||||
isRange?: boolean;
|
||||
}
|
||||
|
||||
interface PortInfo {
|
||||
PublicPort?: number;
|
||||
PrivatePort?: number;
|
||||
publicPort?: number;
|
||||
privatePort?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format Docker port mappings, collapsing consecutive ranges of 3+ ports.
|
||||
* Accepts both Docker API format (PublicPort/PrivatePort) and camelCase (publicPort/privatePort).
|
||||
* e.g. 8080:8080, 8081:8081, 8082:8082 → 8080-8082:8080-8082
|
||||
* But 80:80, 81:81 stay as individual ports (only 2 consecutive).
|
||||
*/
|
||||
export function formatPorts(ports: PortInfo[] | undefined | null): PortMapping[] {
|
||||
if (!ports || ports.length === 0) return [];
|
||||
const seen = new Set<string>();
|
||||
const individual = ports
|
||||
.filter(p => (p.PublicPort || p.publicPort))
|
||||
.map(p => ({
|
||||
publicPort: p.PublicPort || p.publicPort!,
|
||||
privatePort: p.PrivatePort || p.privatePort!,
|
||||
display: `${p.PublicPort || p.publicPort}:${p.PrivatePort || p.privatePort}`
|
||||
}))
|
||||
.filter(p => {
|
||||
const key = p.display;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
})
|
||||
.sort((a, b) => a.publicPort - b.publicPort);
|
||||
|
||||
// Collapse consecutive port ranges (3+ ports only)
|
||||
if (individual.length <= 1) return individual;
|
||||
|
||||
const result: PortMapping[] = [];
|
||||
let rangeStart = 0;
|
||||
let rangeEnd = 0;
|
||||
|
||||
for (let i = 1; i < individual.length; i++) {
|
||||
const curr = individual[i];
|
||||
const start = individual[rangeStart];
|
||||
const prev = individual[rangeEnd];
|
||||
const offset = curr.publicPort - start.publicPort;
|
||||
const expectedPrivate = start.privatePort + offset;
|
||||
if (curr.publicPort === prev.publicPort + 1 && curr.privatePort === expectedPrivate) {
|
||||
rangeEnd = i;
|
||||
} else {
|
||||
flushRange(individual, rangeStart, rangeEnd, result);
|
||||
rangeStart = i;
|
||||
rangeEnd = i;
|
||||
}
|
||||
}
|
||||
flushRange(individual, rangeStart, rangeEnd, result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function flushRange(items: PortMapping[], start: number, end: number, result: PortMapping[]) {
|
||||
const rangeLen = end - start + 1;
|
||||
if (rangeLen >= 3) {
|
||||
// Collapse into range
|
||||
result.push({
|
||||
publicPort: items[start].publicPort,
|
||||
privatePort: items[start].privatePort,
|
||||
display: `${items[start].publicPort}-${items[end].publicPort}:${items[start].privatePort}-${items[end].privatePort}`,
|
||||
isRange: true
|
||||
});
|
||||
} else {
|
||||
// Keep as individual ports
|
||||
for (let i = start; i <= end; i++) {
|
||||
result.push(items[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,6 @@
|
||||
import { getLabelColor, getLabelBgColor } from '$lib/utils/label-colors';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import MultiSelectFilter from '$lib/components/MultiSelectFilter.svelte';
|
||||
import { appSettings } from '$lib/stores/settings';
|
||||
|
||||
const LABEL_FILTER_STORAGE_KEY = 'dockhand-dashboard-label-filter';
|
||||
|
||||
@@ -211,10 +210,10 @@
|
||||
if (filterLabels.length === 0) {
|
||||
return tiles;
|
||||
}
|
||||
const matchFn = $appSettings.labelFilterMode === 'all'
|
||||
? (tileLabels: string[]) => filterLabels.every(label => tileLabels.includes(label))
|
||||
: (tileLabels: string[]) => filterLabels.some(label => tileLabels.includes(label));
|
||||
return tiles.filter(t => matchFn(t.stats?.labels || []));
|
||||
return tiles.filter(t => {
|
||||
const tileLabels = t.stats?.labels || [];
|
||||
return tileLabels.some(label => filterLabels.includes(label));
|
||||
});
|
||||
});
|
||||
|
||||
// Filter grid items based on selected labels
|
||||
@@ -222,12 +221,11 @@
|
||||
if (filterLabels.length === 0) {
|
||||
return gridItems;
|
||||
}
|
||||
const matchFn = $appSettings.labelFilterMode === 'all'
|
||||
? (tileLabels: string[]) => filterLabels.every(label => tileLabels.includes(label))
|
||||
: (tileLabels: string[]) => filterLabels.some(label => tileLabels.includes(label));
|
||||
// Filter to only show tiles whose environments have at least one matching label
|
||||
return gridItems.filter(item => {
|
||||
const tile = tiles.find(t => t.id === item.id);
|
||||
return matchFn(tile?.stats?.labels || []);
|
||||
const tileLabels = tile?.stats?.labels || [];
|
||||
return tileLabels.some(label => filterLabels.includes(label));
|
||||
});
|
||||
});
|
||||
const orderedGridItems = $derived.by(() => {
|
||||
|
||||
@@ -1,164 +0,0 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { generateApiToken, listUserTokens } from '$lib/server/api-tokens';
|
||||
import { isAuthEnabled, verifyPassword } from '$lib/server/auth';
|
||||
import { getUser } from '$lib/server/db';
|
||||
import { audit } from '$lib/server/audit';
|
||||
import { getRequestContext } from '$lib/server/request-context';
|
||||
|
||||
// Password confirmation rate limiting (per userId)
|
||||
const pwFailCounts = new Map<number, { count: number; firstFail: number }>();
|
||||
const pwCooldowns = new Map<number, number>();
|
||||
const PW_FAIL_WINDOW = 60_000; // 1-minute sliding window
|
||||
const PW_FAIL_MAX = 5; // max failures per window
|
||||
const PW_COOLDOWN = 5 * 60 * 1000; // 5-minute cooldown
|
||||
|
||||
const MAX_TOKENS_PER_USER = 25;
|
||||
|
||||
// Periodic cleanup
|
||||
setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [id, until] of pwCooldowns) {
|
||||
if (now > until) pwCooldowns.delete(id);
|
||||
}
|
||||
for (const [id, entry] of pwFailCounts) {
|
||||
if (now - entry.firstFail > PW_FAIL_WINDOW) pwFailCounts.delete(id);
|
||||
}
|
||||
}, PW_COOLDOWN).unref?.();
|
||||
|
||||
function isPwRateLimited(userId: number): boolean {
|
||||
const until = pwCooldowns.get(userId);
|
||||
if (!until) return false;
|
||||
if (Date.now() > until) {
|
||||
pwCooldowns.delete(userId);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function recordPwFailure(userId: number): void {
|
||||
const now = Date.now();
|
||||
const entry = pwFailCounts.get(userId);
|
||||
if (!entry || now - entry.firstFail > PW_FAIL_WINDOW) {
|
||||
pwFailCounts.set(userId, { count: 1, firstFail: now });
|
||||
return;
|
||||
}
|
||||
entry.count++;
|
||||
if (entry.count >= PW_FAIL_MAX) {
|
||||
pwCooldowns.set(userId, now + PW_COOLDOWN);
|
||||
pwFailCounts.delete(userId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/auth/tokens - List the current user's API tokens
|
||||
*/
|
||||
export const GET: RequestHandler = async ({ cookies }) => {
|
||||
const authEnabled = await isAuthEnabled();
|
||||
if (!authEnabled) {
|
||||
return json({ error: 'Authentication is not enabled' }, { status: 400 });
|
||||
}
|
||||
|
||||
const auth = await authorize(cookies);
|
||||
if (!auth.isAuthenticated || !auth.user) {
|
||||
return json({ error: 'Authentication required' }, { status: 401 });
|
||||
}
|
||||
|
||||
const tokens = await listUserTokens(auth.user.id);
|
||||
return json(tokens);
|
||||
};
|
||||
|
||||
/**
|
||||
* POST /api/auth/tokens - Create a new API token
|
||||
*/
|
||||
export const POST: RequestHandler = async (event) => {
|
||||
const { cookies, request } = event;
|
||||
|
||||
const authEnabled = await isAuthEnabled();
|
||||
if (!authEnabled) {
|
||||
return json({ error: 'Authentication is not enabled' }, { status: 400 });
|
||||
}
|
||||
|
||||
const auth = await authorize(cookies);
|
||||
if (!auth.isAuthenticated || !auth.user) {
|
||||
return json({ error: 'Authentication required' }, { status: 401 });
|
||||
}
|
||||
|
||||
// Token creation requires a cookie session — a Bearer token cannot create new tokens
|
||||
const reqCtx = getRequestContext();
|
||||
if (reqCtx?.authMethod === 'bearer') {
|
||||
return json({ error: 'Token creation requires a session login, not a Bearer token' }, { status: 403 });
|
||||
}
|
||||
|
||||
let body: any;
|
||||
try {
|
||||
body = await request.json();
|
||||
} catch {
|
||||
return json({ error: 'Invalid request body' }, { status: 400 });
|
||||
}
|
||||
const { name, expiresAt, password } = body;
|
||||
|
||||
// Local users must confirm their password to create tokens
|
||||
// SSO/OIDC and LDAP users skip this (they authenticated via their IdP)
|
||||
if (auth.user.provider === 'local') {
|
||||
if (isPwRateLimited(auth.user.id)) {
|
||||
return json({ error: 'Too many failed password attempts. Try again later.' }, { status: 429 });
|
||||
}
|
||||
if (!password || typeof password !== 'string') {
|
||||
return json({ error: 'Password is required to create an API token' }, { status: 400 });
|
||||
}
|
||||
const dbUser = await getUser(auth.user.id);
|
||||
if (!dbUser) {
|
||||
return json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
const valid = await verifyPassword(password, dbUser.passwordHash);
|
||||
if (!valid) {
|
||||
recordPwFailure(auth.user.id);
|
||||
return json({ error: 'Invalid password' }, { status: 403 });
|
||||
}
|
||||
}
|
||||
|
||||
// L2: Per-user token count limit
|
||||
const existingTokens = await listUserTokens(auth.user.id);
|
||||
if (existingTokens.length >= MAX_TOKENS_PER_USER) {
|
||||
return json({ error: `Maximum of ${MAX_TOKENS_PER_USER} API tokens per user` }, { status: 400 });
|
||||
}
|
||||
|
||||
// Validate name
|
||||
if (!name || typeof name !== 'string' || name.trim().length === 0) {
|
||||
return json({ error: 'Token name is required' }, { status: 400 });
|
||||
}
|
||||
if (name.length > 255) {
|
||||
return json({ error: 'Token name must be 255 characters or less' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Validate expiration
|
||||
if (expiresAt) {
|
||||
const expiryDate = new Date(expiresAt);
|
||||
if (isNaN(expiryDate.getTime())) {
|
||||
return json({ error: 'Invalid expiration date' }, { status: 400 });
|
||||
}
|
||||
if (expiryDate <= new Date()) {
|
||||
return json({ error: 'Expiration date must be in the future' }, { status: 400 });
|
||||
}
|
||||
}
|
||||
|
||||
const result = await generateApiToken(
|
||||
auth.user.id,
|
||||
name.trim(),
|
||||
expiresAt || null
|
||||
);
|
||||
|
||||
await audit(event, 'create', 'api_token', {
|
||||
entityId: String(result.id),
|
||||
entityName: name.trim(),
|
||||
description: `API token "${name.trim()}" created`
|
||||
});
|
||||
|
||||
return json({
|
||||
id: result.id,
|
||||
token: result.token,
|
||||
tokenPrefix: result.tokenPrefix
|
||||
}, { status: 201, headers: { 'Cache-Control': 'no-store' } });
|
||||
};
|
||||
@@ -1,47 +0,0 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { revokeApiToken } from '$lib/server/api-tokens';
|
||||
import { isAuthEnabled } from '$lib/server/auth';
|
||||
import { getRequestContext } from '$lib/server/request-context';
|
||||
import { audit } from '$lib/server/audit';
|
||||
|
||||
/**
|
||||
* DELETE /api/auth/tokens/[id] - Revoke an API token
|
||||
*/
|
||||
export const DELETE: RequestHandler = async (event) => {
|
||||
const { cookies, params } = event;
|
||||
|
||||
const authEnabled = await isAuthEnabled();
|
||||
if (!authEnabled) {
|
||||
return json({ error: 'Authentication is not enabled' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Bearer tokens cannot manage tokens (prevent leaked token from revoking others)
|
||||
const reqCtx = getRequestContext();
|
||||
if (reqCtx?.authMethod === 'bearer') {
|
||||
return json({ error: 'Token management requires a cookie session' }, { status: 403 });
|
||||
}
|
||||
|
||||
const auth = await authorize(cookies);
|
||||
if (!auth.isAuthenticated || !auth.user) {
|
||||
return json({ error: 'Authentication required' }, { status: 401 });
|
||||
}
|
||||
|
||||
const tokenId = parseInt(params.id);
|
||||
if (isNaN(tokenId)) {
|
||||
return json({ error: 'Invalid token ID' }, { status: 400 });
|
||||
}
|
||||
|
||||
const success = await revokeApiToken(tokenId, auth.user.id, auth.isAdmin);
|
||||
if (!success) {
|
||||
return json({ error: 'Token not found or access denied' }, { status: 404 });
|
||||
}
|
||||
|
||||
await audit(event, 'delete', 'api_token', {
|
||||
entityId: params.id,
|
||||
description: `API token revoked`
|
||||
});
|
||||
|
||||
return json({ success: true });
|
||||
};
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
deleteAutoUpdateSchedule
|
||||
} from '$lib/server/db';
|
||||
import { registerSchedule, unregisterSchedule } from '$lib/server/scheduler';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
|
||||
export const GET: RequestHandler = async ({ params, url }) => {
|
||||
try {
|
||||
@@ -39,12 +38,7 @@ export const GET: RequestHandler = async ({ params, url }) => {
|
||||
}
|
||||
};
|
||||
|
||||
export const POST: RequestHandler = async ({ params, url, request, cookies }) => {
|
||||
const auth = await authorize(cookies);
|
||||
if (auth.authEnabled && !await auth.can('schedules', 'edit')) {
|
||||
return json({ error: 'Permission denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
export const POST: RequestHandler = async ({ params, url, request }) => {
|
||||
try {
|
||||
const containerName = decodeURIComponent(params.containerName);
|
||||
const envIdParam = url.searchParams.get('env');
|
||||
@@ -66,7 +60,7 @@ export const POST: RequestHandler = async ({ params, url, request, cookies }) =>
|
||||
let scheduleType: 'daily' | 'weekly' | 'custom' = 'custom';
|
||||
if (cronExpression) {
|
||||
const parts = cronExpression.split(' ');
|
||||
if (parts.length === 5) {
|
||||
if (parts.length >= 5) {
|
||||
const [, , day, month, dow] = parts;
|
||||
if (dow !== '*' && day === '*' && month === '*') {
|
||||
scheduleType = 'weekly';
|
||||
@@ -107,12 +101,7 @@ export const POST: RequestHandler = async ({ params, url, request, cookies }) =>
|
||||
}
|
||||
};
|
||||
|
||||
export const DELETE: RequestHandler = async ({ params, url, cookies }) => {
|
||||
const auth = await authorize(cookies);
|
||||
if (auth.authEnabled && !await auth.can('schedules', 'edit')) {
|
||||
return json({ error: 'Permission denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
export const DELETE: RequestHandler = async ({ params, url }) => {
|
||||
try {
|
||||
const containerName = decodeURIComponent(params.containerName);
|
||||
const envIdParam = url.searchParams.get('env');
|
||||
|
||||
@@ -3,7 +3,6 @@ import { listContainers, createContainer, pullImage, EnvironmentNotFoundError, D
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { auditContainer } from '$lib/server/audit';
|
||||
import { hasEnvironments } from '$lib/server/db';
|
||||
import { isHiddenByLabel } from '$lib/server/container-labels';
|
||||
import type { RequestHandler } from './$types';
|
||||
|
||||
export const GET: RequestHandler = async ({ url, cookies }) => {
|
||||
@@ -35,9 +34,7 @@ export const GET: RequestHandler = async ({ url, cookies }) => {
|
||||
|
||||
try {
|
||||
const containers = await listContainers(all, envIdNum);
|
||||
// Filter out containers with dockhand.hidden=true label
|
||||
const visible = containers.filter(c => !isHiddenByLabel(c.labels));
|
||||
return json(visible);
|
||||
return json(containers);
|
||||
} catch (error: any) {
|
||||
// Return 404 for missing environment so frontend can clear stale localStorage
|
||||
if (error instanceof EnvironmentNotFoundError) {
|
||||
|
||||
@@ -4,8 +4,7 @@ import {
|
||||
removeContainer,
|
||||
getContainerLogs
|
||||
} from '$lib/server/docker';
|
||||
import { deleteAutoUpdateSchedule, getAutoUpdateSetting, getSecretKeysToMask, removePendingContainerUpdate } from '$lib/server/db';
|
||||
import { getStackComposeFile } from '$lib/server/stacks';
|
||||
import { deleteAutoUpdateSchedule, getAutoUpdateSetting, removePendingContainerUpdate } from '$lib/server/db';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { auditContainer } from '$lib/server/audit';
|
||||
import { unregisterSchedule } from '$lib/server/scheduler';
|
||||
@@ -34,26 +33,6 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
|
||||
try {
|
||||
|
||||
const details = await inspectContainer(params.id, envIdNum);
|
||||
|
||||
// Mask secret env vars for containers belonging to a Compose stack.
|
||||
// Uses compose file parsing to detect interpolation (e.g., MYSQL_PASSWORD=${db_secret}).
|
||||
const stackName = details.Config?.Labels?.['com.docker.compose.project'];
|
||||
if (stackName && Array.isArray(details.Config?.Env)) {
|
||||
const composeResult = await getStackComposeFile(stackName, envIdNum).catch(() => null);
|
||||
const secretKeys = await getSecretKeysToMask(stackName, envIdNum, composeResult?.content);
|
||||
if (secretKeys.size > 0) {
|
||||
details.Config.Env = details.Config.Env.map((entry: string) => {
|
||||
const eqIdx = entry.indexOf('=');
|
||||
if (eqIdx === -1) return entry;
|
||||
const key = entry.substring(0, eqIdx);
|
||||
if (secretKeys.has(key)) {
|
||||
return `${key}=***`;
|
||||
}
|
||||
return entry;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return json(details);
|
||||
} catch (error: any) {
|
||||
if (error?.statusCode === 404) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import { putContainerArchive, inspectContainer, execInContainer } from '$lib/server/docker';
|
||||
import { putContainerArchive } from '$lib/server/docker';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { validateDockerIdParam } from '$lib/server/docker-validation';
|
||||
import type { RequestHandler } from './$types';
|
||||
@@ -111,15 +111,6 @@ export const POST: RequestHandler = async ({ params, url, request, cookies }) =>
|
||||
return json({ error: 'No files provided' }, { status: 400 });
|
||||
}
|
||||
|
||||
// We'll inspect the container once to determine its default user
|
||||
let defaultUser: string | undefined;
|
||||
try {
|
||||
const inspectData = await inspectContainer(params.id, envIdNum);
|
||||
defaultUser = inspectData.Config.User || undefined;
|
||||
} catch (e) {
|
||||
console.warn('Failed to inspect container for user info', e);
|
||||
}
|
||||
|
||||
// For simplicity, we'll upload files one at a time
|
||||
// A more sophisticated implementation could pack multiple files into one tar
|
||||
const uploaded: string[] = [];
|
||||
@@ -137,22 +128,6 @@ export const POST: RequestHandler = async ({ params, url, request, cookies }) =>
|
||||
envId ? parseInt(envId) : undefined
|
||||
);
|
||||
|
||||
// chown the uploaded file
|
||||
if (defaultUser) {
|
||||
const targetPath = path.endsWith('/') ? `${path}${file.name}` : `${path}/${file.name}`;
|
||||
const ownerGroup = defaultUser.includes(':') ? defaultUser : `${defaultUser}:${defaultUser}`;
|
||||
try {
|
||||
await execInContainer(
|
||||
params.id,
|
||||
['chown', '-R', ownerGroup, targetPath],
|
||||
envId ? parseInt(envId) : undefined,
|
||||
'root'
|
||||
);
|
||||
} catch (e) {
|
||||
console.warn('Failed to set ownership on', targetPath, e);
|
||||
}
|
||||
}
|
||||
|
||||
uploaded.push(file.name);
|
||||
} catch (err: any) {
|
||||
errors.push(`${file.name}: ${err.message}`);
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { inspectContainer } from '$lib/server/docker';
|
||||
import { getSecretKeysToMask } from '$lib/server/db';
|
||||
import { getStackComposeFile } from '$lib/server/stacks';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { validateDockerIdParam } from '$lib/server/docker-validation';
|
||||
|
||||
@@ -22,26 +20,6 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
|
||||
|
||||
try {
|
||||
const containerData = await inspectContainer(params.id, envIdNum);
|
||||
|
||||
// Mask secret env vars for containers belonging to a Compose stack.
|
||||
// Uses compose file parsing to detect interpolation (e.g., MYSQL_PASSWORD=${db_secret}).
|
||||
const stackName = containerData.Config?.Labels?.['com.docker.compose.project'];
|
||||
if (stackName && Array.isArray(containerData.Config?.Env)) {
|
||||
const composeResult = await getStackComposeFile(stackName, envIdNum).catch(() => null);
|
||||
const secretKeys = await getSecretKeysToMask(stackName, envIdNum, composeResult?.content);
|
||||
if (secretKeys.size > 0) {
|
||||
containerData.Config.Env = containerData.Config.Env.map((entry: string) => {
|
||||
const eqIdx = entry.indexOf('=');
|
||||
if (eqIdx === -1) return entry;
|
||||
const key = entry.substring(0, eqIdx);
|
||||
if (secretKeys.has(key)) {
|
||||
return `${key}=***`;
|
||||
}
|
||||
return entry;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return json(containerData);
|
||||
} catch (error) {
|
||||
console.error('Failed to inspect container:', error);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import { inspectContainer, pullImage, updateContainer, type CreateContainerOptions } from '$lib/server/docker';
|
||||
import { pullImage, updateContainer, type CreateContainerOptions } from '$lib/server/docker';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { auditContainer } from '$lib/server/audit';
|
||||
import { removePendingContainerUpdate } from '$lib/server/db';
|
||||
@@ -25,29 +25,6 @@ export const POST: RequestHandler = async (event) => {
|
||||
const body = await request.json();
|
||||
const { startAfterUpdate, repullImage, ...options } = body;
|
||||
|
||||
// Resolve masked secret values (***) back to real values from the current container.
|
||||
// The GET endpoint masks secrets in Config.Env, so the edit modal sends *** for unchanged secrets.
|
||||
if (Array.isArray(options.env) && options.env.some((e: string) => e.endsWith('=***'))) {
|
||||
const currentData = await inspectContainer(params.id, envIdNum);
|
||||
const currentEnvMap = new Map<string, string>();
|
||||
for (const entry of currentData.Config?.Env || []) {
|
||||
const eqIdx = entry.indexOf('=');
|
||||
if (eqIdx !== -1) {
|
||||
currentEnvMap.set(entry.substring(0, eqIdx), entry.substring(eqIdx + 1));
|
||||
}
|
||||
}
|
||||
options.env = options.env.map((entry: string) => {
|
||||
const eqIdx = entry.indexOf('=');
|
||||
if (eqIdx === -1) return entry;
|
||||
const key = entry.substring(0, eqIdx);
|
||||
const value = entry.substring(eqIdx + 1);
|
||||
if (value === '***' && currentEnvMap.has(key)) {
|
||||
return `${key}=${currentEnvMap.get(key)}`;
|
||||
}
|
||||
return entry;
|
||||
});
|
||||
}
|
||||
|
||||
if (repullImage) {
|
||||
console.log(`Pulling image...`);
|
||||
try {
|
||||
|
||||
@@ -15,7 +15,6 @@ import { auditContainer } from '$lib/server/audit';
|
||||
import { getScannerSettings, scanImage } from '$lib/server/scanner';
|
||||
import { saveVulnerabilityScan, removePendingContainerUpdate, type VulnerabilityCriteria } from '$lib/server/db';
|
||||
import { parseImageNameAndTag, shouldBlockUpdate, combineScanSummaries, isSystemContainer } from '$lib/server/scheduler/tasks/update-utils';
|
||||
import { isUpdateDisabledByLabel } from '$lib/server/container-labels';
|
||||
import { recreateContainer } from '$lib/server/scheduler/tasks/container-update';
|
||||
import { createJob, appendLine, completeJob, failJob } from '$lib/server/jobs';
|
||||
|
||||
@@ -174,22 +173,6 @@ export const POST: RequestHandler = async (event) => {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip containers with dockhand.update=false label
|
||||
if (isUpdateDisabledByLabel(config.Labels)) {
|
||||
sendData({
|
||||
type: 'progress',
|
||||
containerId,
|
||||
containerName,
|
||||
step: 'skipped',
|
||||
current: i + 1,
|
||||
total: containerIds.length,
|
||||
success: true,
|
||||
message: `Skipping ${containerName} - dockhand.update=false label`
|
||||
});
|
||||
skippedCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip digest-pinned images - they are explicitly locked to a specific version
|
||||
if (isDigestBasedImage(imageName)) {
|
||||
sendData({
|
||||
|
||||
@@ -4,7 +4,6 @@ import { authorize } from '$lib/server/authorize';
|
||||
import { listContainers, pullImage, inspectContainer } from '$lib/server/docker';
|
||||
import { auditContainer } from '$lib/server/audit';
|
||||
import { recreateContainer } from '$lib/server/scheduler/tasks/container-update';
|
||||
import { isUpdateDisabledByLabel } from '$lib/server/container-labels';
|
||||
|
||||
export interface BatchUpdateResult {
|
||||
containerId: string;
|
||||
@@ -63,17 +62,6 @@ export const POST: RequestHandler = async (event) => {
|
||||
const imageName = config.Image;
|
||||
const containerName = container.name;
|
||||
|
||||
// Skip containers with dockhand.update=false label
|
||||
if (isUpdateDisabledByLabel(config.Labels)) {
|
||||
results.push({
|
||||
containerId,
|
||||
containerName,
|
||||
success: true,
|
||||
error: 'Skipped - dockhand.update=false label'
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// Pull latest image first
|
||||
try {
|
||||
await pullImage(imageName, undefined, envIdNum);
|
||||
|
||||
@@ -4,7 +4,6 @@ import { authorize } from '$lib/server/authorize';
|
||||
import { listContainers, inspectContainer, checkImageUpdateAvailable } from '$lib/server/docker';
|
||||
import { clearPendingContainerUpdates, addPendingContainerUpdate } from '$lib/server/db';
|
||||
import { isSystemContainer } from '$lib/server/scheduler/tasks/update-utils';
|
||||
import { isUpdateDisabledByLabel } from '$lib/server/container-labels';
|
||||
import { createJobResponse } from '$lib/server/sse';
|
||||
|
||||
export interface UpdateCheckResult {
|
||||
@@ -17,7 +16,6 @@ export interface UpdateCheckResult {
|
||||
error?: string;
|
||||
isLocalImage?: boolean;
|
||||
systemContainer?: 'dockhand' | 'hawser' | null;
|
||||
updateDisabled?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -66,7 +64,6 @@ export const POST: RequestHandler = async ({ url, cookies, request }) => {
|
||||
}
|
||||
|
||||
const result = await checkImageUpdateAvailable(imageName, currentImageId, envIdNum);
|
||||
const updateDisabled = isUpdateDisabledByLabel(inspectData.Config?.Labels);
|
||||
|
||||
return {
|
||||
containerId: container.id,
|
||||
@@ -77,8 +74,7 @@ export const POST: RequestHandler = async ({ url, cookies, request }) => {
|
||||
newDigest: result.registryDigest,
|
||||
error: result.error,
|
||||
isLocalImage: result.isLocalImage,
|
||||
systemContainer: isSystemContainer(imageName) || null,
|
||||
updateDisabled
|
||||
systemContainer: isSystemContainer(imageName) || null
|
||||
};
|
||||
} catch (error: any) {
|
||||
return {
|
||||
@@ -106,12 +102,12 @@ export const POST: RequestHandler = async ({ url, cookies, request }) => {
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, containers.length) }, () => runNext()));
|
||||
|
||||
const updatesFound = results.filter(r => r.hasUpdate && !r.systemContainer && !r.updateDisabled).length;
|
||||
const updatesFound = results.filter(r => r.hasUpdate && !r.systemContainer).length;
|
||||
|
||||
// Save containers with updates to the database for persistence
|
||||
if (envIdNum) {
|
||||
for (const result of results) {
|
||||
if (result.hasUpdate && !result.systemContainer && !result.updateDisabled) {
|
||||
if (result.hasUpdate && !result.systemContainer) {
|
||||
await addPendingContainerUpdate(
|
||||
envIdNum,
|
||||
result.containerId,
|
||||
|
||||
@@ -3,7 +3,6 @@ import type { RequestHandler } from './$types';
|
||||
import { getEnvironments, getEnvironmentByName, createEnvironment, assignUserRole, getRoleByName, getEnvironmentPublicIps, setEnvironmentPublicIp, getEnvUpdateCheckSettings, getEnvironmentTimezone, getImagePruneSettings, type Environment } from '$lib/server/db';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { auditEnvironment } from '$lib/server/audit';
|
||||
import { invalidateTokenCacheForUser } from '$lib/server/api-tokens';
|
||||
import { refreshSubprocessEnvironments } from '$lib/server/subprocess-manager';
|
||||
import { serializeLabels, parseLabels, MAX_LABELS } from '$lib/utils/label-colors';
|
||||
import { cleanPem } from '$lib/utils/pem';
|
||||
@@ -131,7 +130,6 @@ export const POST: RequestHandler = async (event) => {
|
||||
const adminRole = await getRoleByName('Admin');
|
||||
if (adminRole) {
|
||||
await assignUserRole(user.id, adminRole.id, env.id);
|
||||
invalidateTokenCacheForUser(user.id);
|
||||
}
|
||||
} catch (roleError) {
|
||||
// Log but don't fail - environment was created successfully
|
||||
|
||||
@@ -115,7 +115,6 @@ export const DELETE: RequestHandler = async (event) => {
|
||||
|
||||
// Delete git stack clone directories before cascade deletes the DB rows
|
||||
const stacks = await getGitStacksByRepositoryId(id);
|
||||
console.log(`[GitStack] Repository "${repository.name}" (id=${id}) deletion affects ${stacks.length} stacks: ${stacks.map(s => s.stackName).join(', ')}`);
|
||||
for (const stack of stacks) {
|
||||
await deleteGitStackFiles(stack.id, stack.stackName, stack.environmentId);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
getHostname
|
||||
} from '$lib/server/license';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { clearTokenCache } from '$lib/server/api-tokens';
|
||||
|
||||
// GET /api/license - Get current license status
|
||||
// Any authenticated user can view license status (needed to determine if RBAC applies)
|
||||
@@ -60,9 +59,6 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
|
||||
);
|
||||
}
|
||||
|
||||
// Permission model changes between free/enterprise — clear cached tokens
|
||||
clearTokenCache();
|
||||
|
||||
return json({
|
||||
success: true,
|
||||
license: result.license
|
||||
@@ -85,8 +81,6 @@ export const DELETE: RequestHandler = async ({ cookies }) => {
|
||||
|
||||
try {
|
||||
await deactivateLicense();
|
||||
// Permission model changes between free/enterprise — clear cached tokens
|
||||
clearTokenCache();
|
||||
return json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('Error deactivating license:', error);
|
||||
|
||||
@@ -2,7 +2,6 @@ import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from '@sveltejs/kit';
|
||||
import { getUser, updateUser as dbUpdateUser, deleteUserSessions, userHasAdminRole } from '$lib/server/db';
|
||||
import { validateSession, hashPassword, isAuthEnabled } from '$lib/server/auth';
|
||||
import { invalidateTokenCacheForUser } from '$lib/server/api-tokens';
|
||||
|
||||
// GET /api/profile - Get current user's profile
|
||||
export const GET: RequestHandler = async ({ cookies }) => {
|
||||
@@ -86,9 +85,8 @@ export const PUT: RequestHandler = async ({ request, cookies }) => {
|
||||
}
|
||||
|
||||
updateData.passwordHash = await hashPassword(data.newPassword);
|
||||
// Invalidate other sessions and token cache on password change
|
||||
await deleteUserSessions(currentUser.id);
|
||||
invalidateTokenCacheForUser(currentUser.id);
|
||||
// Invalidate other sessions on password change
|
||||
deleteUserSessions(currentUser.id);
|
||||
}
|
||||
|
||||
const user = await dbUpdateUser(currentUser.id, updateData);
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { auditRole } from '$lib/server/audit';
|
||||
import { computeAuditDiff } from '$lib/utils/diff';
|
||||
import { clearTokenCache } from '$lib/server/api-tokens';
|
||||
|
||||
// GET /api/roles/[id] - Get a specific role
|
||||
export const GET: RequestHandler = async ({ params, cookies }) => {
|
||||
@@ -76,9 +75,6 @@ export const PUT: RequestHandler = async (event) => {
|
||||
return json({ error: 'Failed to update role' }, { status: 500 });
|
||||
}
|
||||
|
||||
// Clear token cache — any cached user with this role has stale permissions
|
||||
clearTokenCache();
|
||||
|
||||
// Compute diff for audit
|
||||
const diff = computeAuditDiff(existingRole, role);
|
||||
|
||||
@@ -132,9 +128,6 @@ export const DELETE: RequestHandler = async (event) => {
|
||||
return json({ error: 'Failed to delete role' }, { status: 500 });
|
||||
}
|
||||
|
||||
// Clear token cache — users with this role may have stale cached permissions
|
||||
clearTokenCache();
|
||||
|
||||
// Audit log
|
||||
await auditRole(event, 'delete', id, role.name);
|
||||
|
||||
|
||||
@@ -13,14 +13,8 @@ import {
|
||||
deleteImagePruneSettings
|
||||
} from '$lib/server/db';
|
||||
import { unregisterSchedule } from '$lib/server/scheduler';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
|
||||
export const DELETE: RequestHandler = async ({ params, cookies }) => {
|
||||
const auth = await authorize(cookies);
|
||||
if (auth.authEnabled && !await auth.can('schedules', 'edit')) {
|
||||
return json({ error: 'Permission denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
export const DELETE: RequestHandler = async ({ params }) => {
|
||||
try {
|
||||
const { type, id } = params;
|
||||
const scheduleId = parseInt(id, 10);
|
||||
|
||||
@@ -11,14 +11,8 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { triggerContainerUpdate, triggerGitStackSync, triggerSystemJob, triggerEnvUpdateCheck, triggerImagePrune } from '$lib/server/scheduler';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
|
||||
export const POST: RequestHandler = async ({ params, cookies }) => {
|
||||
const auth = await authorize(cookies);
|
||||
if (auth.authEnabled && !await auth.can('schedules', 'run')) {
|
||||
return json({ error: 'Permission denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
export const POST: RequestHandler = async ({ params }) => {
|
||||
try {
|
||||
const { type, id } = params;
|
||||
const scheduleId = parseInt(id, 10);
|
||||
|
||||
@@ -7,14 +7,8 @@ import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { getAutoUpdateSettingById, updateAutoUpdateSettingById, getGitStack, updateGitStack, getEnvUpdateCheckSettings, setEnvUpdateCheckSettings, getImagePruneSettings, setImagePruneSettings } from '$lib/server/db';
|
||||
import { registerSchedule, unregisterSchedule } from '$lib/server/scheduler';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
|
||||
export const POST: RequestHandler = async ({ params, cookies }) => {
|
||||
const auth = await authorize(cookies);
|
||||
if (auth.authEnabled && !await auth.can('schedules', 'edit')) {
|
||||
return json({ error: 'Permission denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
export const POST: RequestHandler = async ({ params }) => {
|
||||
try {
|
||||
const { type, id } = params;
|
||||
const scheduleId = parseInt(id, 10);
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { getScheduleExecution, deleteScheduleExecution } from '$lib/server/db';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
|
||||
export const GET: RequestHandler = async ({ params }) => {
|
||||
try {
|
||||
@@ -29,12 +28,7 @@ export const GET: RequestHandler = async ({ params }) => {
|
||||
}
|
||||
};
|
||||
|
||||
export const DELETE: RequestHandler = async ({ params, cookies }) => {
|
||||
const auth = await authorize(cookies);
|
||||
if (auth.authEnabled && !await auth.can('schedules', 'edit')) {
|
||||
return json({ error: 'Permission denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
export const DELETE: RequestHandler = async ({ params }) => {
|
||||
try {
|
||||
const id = parseInt(params.id, 10);
|
||||
if (isNaN(id)) {
|
||||
|
||||
@@ -1,13 +1,6 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { getAdditionalVolumeBinds } from '$lib/server/mount-dedupe';
|
||||
import {
|
||||
getOwnContainerId,
|
||||
getHostDockerSocket,
|
||||
getOwnDockerHost,
|
||||
getOwnExtraHosts,
|
||||
getOwnNetworkMode
|
||||
} from '$lib/server/host-path';
|
||||
import { getOwnContainerId, getHostDockerSocket, getOwnDockerHost, getOwnNetworkMode } from '$lib/server/host-path';
|
||||
import { buildRegistryAuthHeader, unixSocketRequest, unixSocketStreamRequest } from '$lib/server/docker';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { prefersJSON, sseToJSON } from '$lib/server/sse';
|
||||
@@ -167,7 +160,20 @@ function buildCreateConfig(inspectData: any, newImage: string): any {
|
||||
// Otherwise the old container's hostname is inherited, breaking self-identification
|
||||
delete createConfig.Hostname;
|
||||
|
||||
const additionalBinds = getAdditionalVolumeBinds(hostConfig, inspectData.Mounts || []);
|
||||
// Preserve anonymous volumes from Mounts not in HostConfig.Binds
|
||||
const existingBinds = new Set((hostConfig.Binds || []).map((b: string) => {
|
||||
const parts = b.split(':');
|
||||
return parts.length >= 2 ? parts[1] : parts[0];
|
||||
}));
|
||||
const mounts = inspectData.Mounts || [];
|
||||
const additionalBinds: string[] = [];
|
||||
for (const mount of mounts) {
|
||||
if (mount.Type === 'volume' && mount.Name && mount.Destination) {
|
||||
if (!existingBinds.has(mount.Destination)) {
|
||||
additionalBinds.push(`${mount.Name}:${mount.Destination}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (additionalBinds.length > 0) {
|
||||
createConfig.HostConfig = {
|
||||
...createConfig.HostConfig,
|
||||
@@ -389,12 +395,6 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
|
||||
// Configure updater's Docker access based on connection type
|
||||
const tcpHost = getDockerTcpHost();
|
||||
const updaterHostConfig: Record<string, unknown> = { AutoRemove: true };
|
||||
const updaterExtraHosts = getOwnExtraHosts() ?? undefined;
|
||||
|
||||
if (updaterExtraHosts?.length) {
|
||||
updaterHostConfig.ExtraHosts = updaterExtraHosts;
|
||||
console.log(`[SelfUpdate] Reusing ExtraHosts for updater: ${updaterExtraHosts.join(', ')}`);
|
||||
}
|
||||
|
||||
if (tcpHost) {
|
||||
// TCP: pass DOCKER_HOST so docker CLI in sidecar uses TCP
|
||||
|
||||
@@ -77,10 +77,6 @@ export interface GeneralSettings {
|
||||
// Scanner images
|
||||
defaultGrypeImage: string;
|
||||
defaultTrivyImage: string;
|
||||
// Compose template
|
||||
defaultComposeTemplate: string;
|
||||
// Label filter mode
|
||||
labelFilterMode: 'any' | 'all';
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: Omit<GeneralSettings, 'scheduleRetentionDays' | 'eventRetentionDays' | 'scheduleCleanupCron' | 'eventCleanupCron' | 'scheduleCleanupEnabled' | 'eventCleanupEnabled'> = {
|
||||
@@ -109,26 +105,7 @@ const DEFAULT_SETTINGS: Omit<GeneralSettings, 'scheduleRetentionDays' | 'eventRe
|
||||
externalStackPaths: [],
|
||||
primaryStackLocation: null,
|
||||
defaultGrypeImage: DEFAULT_GRYPE_IMAGE,
|
||||
defaultTrivyImage: DEFAULT_TRIVY_IMAGE,
|
||||
labelFilterMode: 'any' as const,
|
||||
defaultComposeTemplate: `version: "3.8"
|
||||
|
||||
services:
|
||||
app:
|
||||
image: nginx:alpine
|
||||
ports:
|
||||
- "8080:80"
|
||||
environment:
|
||||
- APP_ENV=\${APP_ENV:-production}
|
||||
volumes:
|
||||
- ./html:/usr/share/nginx/html:ro
|
||||
restart: unless-stopped
|
||||
|
||||
# Add more services as needed
|
||||
# networks:
|
||||
# default:
|
||||
# driver: bridge
|
||||
`
|
||||
defaultTrivyImage: DEFAULT_TRIVY_IMAGE
|
||||
};
|
||||
|
||||
const VALID_LIGHT_THEMES = ['default', 'catppuccin', 'rose-pine', 'nord', 'solarized', 'gruvbox', 'alucard', 'github', 'material', 'atom-one'];
|
||||
@@ -182,9 +159,7 @@ export const GET: RequestHandler = async ({ cookies }) => {
|
||||
externalStackPaths,
|
||||
primaryStackLocation,
|
||||
defaultGrypeImage,
|
||||
defaultTrivyImage,
|
||||
defaultComposeTemplate,
|
||||
labelFilterMode
|
||||
defaultTrivyImage
|
||||
] = await Promise.all([
|
||||
getSetting('confirm_destructive'),
|
||||
getSetting('show_stopped_containers'),
|
||||
@@ -217,9 +192,7 @@ export const GET: RequestHandler = async ({ cookies }) => {
|
||||
getExternalStackPaths(),
|
||||
getPrimaryStackLocation(),
|
||||
getSetting('default_grype_image'),
|
||||
getSetting('default_trivy_image'),
|
||||
getSetting('default_compose_template'),
|
||||
getSetting('label_filter_mode')
|
||||
getSetting('default_trivy_image')
|
||||
]);
|
||||
|
||||
const settings: GeneralSettings = {
|
||||
@@ -254,9 +227,7 @@ export const GET: RequestHandler = async ({ cookies }) => {
|
||||
externalStackPaths,
|
||||
primaryStackLocation,
|
||||
defaultGrypeImage: defaultGrypeImage ?? DEFAULT_GRYPE_IMAGE,
|
||||
defaultTrivyImage: defaultTrivyImage ?? DEFAULT_TRIVY_IMAGE,
|
||||
defaultComposeTemplate: defaultComposeTemplate ?? DEFAULT_SETTINGS.defaultComposeTemplate,
|
||||
labelFilterMode: labelFilterMode ?? DEFAULT_SETTINGS.labelFilterMode
|
||||
defaultTrivyImage: defaultTrivyImage ?? DEFAULT_TRIVY_IMAGE
|
||||
};
|
||||
|
||||
return json(settings);
|
||||
@@ -274,7 +245,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { confirmDestructive, showStoppedContainers, highlightUpdates, timeFormat, dateFormat, downloadFormat, defaultGrypeArgs, defaultTrivyArgs, scheduleRetentionDays, eventRetentionDays, scheduleCleanupCron, eventCleanupCron, scheduleCleanupEnabled, eventCleanupEnabled, logBufferSizeKb, defaultTimezone, eventCollectionMode, eventPollInterval, metricsCollectionInterval, lightTheme, darkTheme, font, fontSize, gridFontSize, terminalFont, editorFont, compactPorts, formatLogTimestamps, externalStackPaths, primaryStackLocation, defaultGrypeImage, defaultTrivyImage, defaultComposeTemplate, labelFilterMode } = body;
|
||||
const { confirmDestructive, showStoppedContainers, highlightUpdates, timeFormat, dateFormat, downloadFormat, defaultGrypeArgs, defaultTrivyArgs, scheduleRetentionDays, eventRetentionDays, scheduleCleanupCron, eventCleanupCron, scheduleCleanupEnabled, eventCleanupEnabled, logBufferSizeKb, defaultTimezone, eventCollectionMode, eventPollInterval, metricsCollectionInterval, lightTheme, darkTheme, font, fontSize, gridFontSize, terminalFont, editorFont, compactPorts, formatLogTimestamps, externalStackPaths, primaryStackLocation, defaultGrypeImage, defaultTrivyImage } = body;
|
||||
|
||||
if (confirmDestructive !== undefined) {
|
||||
await setSetting('confirm_destructive', confirmDestructive);
|
||||
@@ -393,12 +364,6 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
|
||||
if (defaultTrivyImage !== undefined && typeof defaultTrivyImage === 'string') {
|
||||
await setSetting('default_trivy_image', defaultTrivyImage);
|
||||
}
|
||||
if (defaultComposeTemplate !== undefined && typeof defaultComposeTemplate === 'string') {
|
||||
await setSetting('default_compose_template', defaultComposeTemplate);
|
||||
}
|
||||
if (labelFilterMode !== undefined && (labelFilterMode === 'any' || labelFilterMode === 'all')) {
|
||||
await setSetting('label_filter_mode', labelFilterMode);
|
||||
}
|
||||
|
||||
// Fetch all settings in parallel for the response
|
||||
const [
|
||||
@@ -433,9 +398,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
|
||||
externalStackPathsVal,
|
||||
primaryStackLocationVal,
|
||||
defaultGrypeImageVal,
|
||||
defaultTrivyImageVal,
|
||||
defaultComposeTemplateVal,
|
||||
labelFilterModeVal
|
||||
defaultTrivyImageVal
|
||||
] = await Promise.all([
|
||||
getSetting('confirm_destructive'),
|
||||
getSetting('show_stopped_containers'),
|
||||
@@ -468,9 +431,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
|
||||
getExternalStackPaths(),
|
||||
getPrimaryStackLocation(),
|
||||
getSetting('default_grype_image'),
|
||||
getSetting('default_trivy_image'),
|
||||
getSetting('default_compose_template'),
|
||||
getSetting('label_filter_mode')
|
||||
getSetting('default_trivy_image')
|
||||
]);
|
||||
|
||||
const settings: GeneralSettings = {
|
||||
@@ -505,9 +466,7 @@ export const POST: RequestHandler = async ({ request, cookies }) => {
|
||||
externalStackPaths: externalStackPathsVal,
|
||||
primaryStackLocation: primaryStackLocationVal,
|
||||
defaultGrypeImage: defaultGrypeImageVal ?? DEFAULT_GRYPE_IMAGE,
|
||||
defaultTrivyImage: defaultTrivyImageVal ?? DEFAULT_TRIVY_IMAGE,
|
||||
defaultComposeTemplate: defaultComposeTemplateVal ?? DEFAULT_SETTINGS.defaultComposeTemplate,
|
||||
labelFilterMode: labelFilterModeVal ?? DEFAULT_SETTINGS.labelFilterMode
|
||||
defaultTrivyImage: defaultTrivyImageVal ?? DEFAULT_TRIVY_IMAGE
|
||||
};
|
||||
|
||||
return json(settings);
|
||||
|
||||
@@ -144,13 +144,10 @@ export const POST: RequestHandler = async (event) => {
|
||||
}
|
||||
|
||||
// ALWAYS save compose file first - deployStack expects it to exist
|
||||
const saveResult = await saveStackComposeFile(name, compose, true, envIdNum, {
|
||||
await saveStackComposeFile(name, compose, true, envIdNum, {
|
||||
composePath: composePath || undefined,
|
||||
envPath: envPath || undefined
|
||||
});
|
||||
if (!saveResult.success) {
|
||||
return json({ error: saveResult.error }, { status: 400 });
|
||||
}
|
||||
|
||||
// Save environment variables BEFORE deploying so they're available during start
|
||||
if (rawEnvContent || (envVars && Array.isArray(envVars) && envVars.length > 0)) {
|
||||
|
||||
@@ -9,7 +9,6 @@ export const DELETE: RequestHandler = async (event) => {
|
||||
const auth = await authorize(cookies);
|
||||
|
||||
const force = url.searchParams.get('force') === 'true';
|
||||
const volumes = url.searchParams.get('volumes') === 'true';
|
||||
const envId = url.searchParams.get('env');
|
||||
const envIdNum = envId ? parseInt(envId) : undefined;
|
||||
|
||||
@@ -25,10 +24,10 @@ export const DELETE: RequestHandler = async (event) => {
|
||||
|
||||
try {
|
||||
const stackName = decodeURIComponent(params.name);
|
||||
const result = await removeStack(stackName, envIdNum, force, volumes);
|
||||
const result = await removeStack(stackName, envIdNum, force);
|
||||
|
||||
// Audit log
|
||||
await auditStack(event, 'delete', stackName, envIdNum, { force, volumes });
|
||||
await auditStack(event, 'delete', stackName, envIdNum, { force });
|
||||
|
||||
if (!result.success) {
|
||||
return json({ success: false, error: result.error }, { status: 400 });
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
} from '$lib/server/db';
|
||||
import { hashPassword, createUserSession } from '$lib/server/auth';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { invalidateTokenCacheForUser } from '$lib/server/api-tokens';
|
||||
import { auditUser } from '$lib/server/audit';
|
||||
|
||||
// GET /api/users - List all users
|
||||
@@ -109,7 +108,6 @@ export const POST: RequestHandler = async (event) => {
|
||||
const adminRole = await getRoleByName('Admin');
|
||||
if (adminRole) {
|
||||
await assignUserRole(user.id, adminRole.id, null);
|
||||
invalidateTokenCacheForUser(user.id);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@ import { hashPassword } from '$lib/server/auth';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { auditUser } from '$lib/server/audit';
|
||||
import { computeAuditDiff } from '$lib/utils/diff';
|
||||
import { invalidateTokenCacheForUser } from '$lib/server/api-tokens';
|
||||
|
||||
// GET /api/users/[id] - Get a specific user
|
||||
// Free for all - local users are needed for basic auth
|
||||
@@ -126,7 +125,6 @@ export const PUT: RequestHandler = async (event) => {
|
||||
if (isDeactivating) {
|
||||
updateData.isActive = false;
|
||||
await deleteUserSessions(userId);
|
||||
invalidateTokenCacheForUser(userId);
|
||||
}
|
||||
|
||||
// Disable authentication
|
||||
@@ -144,7 +142,6 @@ export const PUT: RequestHandler = async (event) => {
|
||||
if (adminRole) {
|
||||
await removeUserRole(userId, adminRole.id, null);
|
||||
}
|
||||
invalidateTokenCacheForUser(userId);
|
||||
}
|
||||
|
||||
return json({
|
||||
@@ -173,10 +170,9 @@ export const PUT: RequestHandler = async (event) => {
|
||||
}
|
||||
if (data.isActive !== undefined) {
|
||||
updateData.isActive = data.isActive;
|
||||
// If deactivating, invalidate all sessions and token cache
|
||||
// If deactivating, invalidate all sessions
|
||||
if (!data.isActive) {
|
||||
await deleteUserSessions(userId);
|
||||
invalidateTokenCacheForUser(userId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -187,9 +183,8 @@ export const PUT: RequestHandler = async (event) => {
|
||||
return json({ error: 'Password must be at least 8 characters' }, { status: 400 });
|
||||
}
|
||||
updateData.passwordHash = await hashPassword(data.password);
|
||||
// Invalidate all sessions and token cache on password change
|
||||
// Invalidate all sessions on password change (except current)
|
||||
await deleteUserSessions(userId);
|
||||
invalidateTokenCacheForUser(userId);
|
||||
}
|
||||
|
||||
const user = await dbUpdateUser(userId, updateData);
|
||||
@@ -203,10 +198,8 @@ export const PUT: RequestHandler = async (event) => {
|
||||
if (adminRole) {
|
||||
if (shouldPromote) {
|
||||
await assignUserRole(userId, adminRole.id, null);
|
||||
invalidateTokenCacheForUser(userId);
|
||||
} else if (shouldDemote) {
|
||||
await removeUserRole(userId, adminRole.id, null);
|
||||
invalidateTokenCacheForUser(userId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,7 +284,6 @@ export const DELETE: RequestHandler = async (event) => {
|
||||
|
||||
// User confirmed - proceed with deletion and disable auth
|
||||
await deleteUserSessions(id);
|
||||
invalidateTokenCacheForUser(id);
|
||||
const deleted = await dbDeleteUser(id);
|
||||
if (!deleted) {
|
||||
return json({ error: 'Failed to delete user' }, { status: 500 });
|
||||
@@ -307,9 +299,8 @@ export const DELETE: RequestHandler = async (event) => {
|
||||
}
|
||||
}
|
||||
|
||||
// Delete all sessions and invalidate token cache
|
||||
// Delete all sessions first
|
||||
await deleteUserSessions(id);
|
||||
invalidateTokenCacheForUser(id);
|
||||
|
||||
const deleted = await dbDeleteUser(id);
|
||||
if (!deleted) {
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
getRole
|
||||
} from '$lib/server/db';
|
||||
import { auditUser } from '$lib/server/audit';
|
||||
import { invalidateTokenCacheForUser } from '$lib/server/api-tokens';
|
||||
|
||||
// GET /api/users/[id]/roles - Get roles assigned to a user
|
||||
export const GET: RequestHandler = async ({ params, cookies }) => {
|
||||
@@ -70,7 +69,6 @@ export const POST: RequestHandler = async (event) => {
|
||||
}
|
||||
|
||||
const userRole = await assignUserRole(userId, roleId, environmentId);
|
||||
invalidateTokenCacheForUser(userId);
|
||||
|
||||
// Audit log - role assigned
|
||||
const role = await getRole(roleId);
|
||||
@@ -119,7 +117,6 @@ export const DELETE: RequestHandler = async (event) => {
|
||||
if (!deleted) {
|
||||
return json({ error: 'Role assignment not found' }, { status: 404 });
|
||||
}
|
||||
invalidateTokenCacheForUser(userId);
|
||||
|
||||
// Audit log - role removed
|
||||
if (user) {
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
import * as Select from '$lib/components/ui/select';
|
||||
import * as Tooltip from '$lib/components/ui/tooltip';
|
||||
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
|
||||
import { formatPorts, type PortMapping } from '$lib/utils/port-format';
|
||||
import MultiSelectFilter from '$lib/components/MultiSelectFilter.svelte';
|
||||
import PageHeader from '$lib/components/PageHeader.svelte';
|
||||
import { Badge } from '$lib/components/ui/badge';
|
||||
@@ -1150,6 +1149,30 @@
|
||||
}
|
||||
}
|
||||
|
||||
interface PortMapping {
|
||||
publicPort: number;
|
||||
privatePort: number;
|
||||
display: string;
|
||||
}
|
||||
|
||||
function formatPorts(ports: ContainerInfo['ports']): PortMapping[] {
|
||||
if (!ports || ports.length === 0) return [];
|
||||
const seen = new Set<string>();
|
||||
return ports
|
||||
.filter(p => p.PublicPort)
|
||||
.map(p => ({
|
||||
publicPort: p.PublicPort,
|
||||
privatePort: p.PrivatePort,
|
||||
display: `${p.PublicPort}:${p.PrivatePort}`
|
||||
}))
|
||||
.filter(p => {
|
||||
const key = p.display;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function extractHostFromUrl(urlString: string): string | null {
|
||||
if (!urlString) return null;
|
||||
|
||||
@@ -1800,7 +1823,7 @@
|
||||
{@const memoryTooltip = stats.memoryCache > 0
|
||||
? `${formatBytes(stats.memoryUsage)} / ${formatBytes(stats.memoryLimit)} (Total: ${formatBytes(stats.memoryRaw)} | Cache: ${formatBytes(stats.memoryCache)})`
|
||||
: `${formatBytes(stats.memoryUsage)} / ${formatBytes(stats.memoryLimit)}`}
|
||||
<span class="text-xs font-mono {stats.memoryPercent > 80 ? 'text-red-500' : stats.memoryPercent > 50 ? 'text-yellow-500' : 'text-muted-foreground'}" title={memoryTooltip}>{formatBytes(stats.memoryUsage)}<span class="text-muted-foreground/50">/{formatBytes(stats.memoryLimit, 0)}</span></span>
|
||||
<span class="text-xs font-mono {stats.memoryPercent > 80 ? 'text-red-500' : stats.memoryPercent > 50 ? 'text-yellow-500' : 'text-muted-foreground'}" title={memoryTooltip}>{formatBytes(stats.memoryUsage)}</span>
|
||||
{:else if container.state === 'running'}
|
||||
<span class="text-xs text-muted-foreground/50">...</span>
|
||||
{:else}
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
|
||||
import { CircleArrowUp, Loader2, AlertCircle, CheckCircle2, XCircle, ChevronDown, ChevronRight, ExternalLink } from 'lucide-svelte';
|
||||
import { appendEnvParam } from '$lib/stores/environment';
|
||||
import { untrack } from 'svelte';
|
||||
import type { VulnerabilityCriteria } from '$lib/server/db';
|
||||
import type { StepType } from '$lib/utils/update-steps';
|
||||
import { getStepLabel, getStepIcon, getStepColor } from '$lib/utils/update-steps';
|
||||
@@ -79,33 +78,11 @@
|
||||
let progress = $state<ContainerProgress[]>([]);
|
||||
let progressListEl = $state<HTMLDivElement | null>(null);
|
||||
let scrollTick = $state(0);
|
||||
let userScrolledUp = $state(false);
|
||||
let currentIndex = $state(0);
|
||||
let totalCount = $state(0);
|
||||
let summary = $state<{ total: number; success: number; failed: number; blocked: number } | null>(null);
|
||||
let errorMessage = $state('');
|
||||
let forceUpdating = $state<Set<string>>(new Set()); // Track containers being force-updated
|
||||
let filterMode = $state<'updated' | 'failed'>('updated');
|
||||
|
||||
let filteredProgress = $derived(
|
||||
!summary
|
||||
? progress
|
||||
: filterMode === 'failed'
|
||||
? progress.filter(p => p.step === 'failed' || p.step === 'blocked')
|
||||
: progress.filter(p => p.step === 'done' || p.success)
|
||||
);
|
||||
|
||||
$effect(() => {
|
||||
// Only track filterMode, not progress — avoid re-running on every SSE update
|
||||
const mode = filterMode;
|
||||
if (mode === 'updated') {
|
||||
untrack(() => {
|
||||
for (const item of progress) {
|
||||
item.showLogs = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function formatPullLog(entry: PullLogEntry): string {
|
||||
// Clarify potentially confusing Docker messages
|
||||
@@ -264,9 +241,6 @@
|
||||
} else if (data.type === 'complete') {
|
||||
status = 'complete';
|
||||
summary = data.summary;
|
||||
for (const item of progress) {
|
||||
item.showLogs = false;
|
||||
}
|
||||
onComplete({ success: successIds, failed: failedIds, blocked: blockedIds });
|
||||
} else if (data.type === 'error') {
|
||||
status = 'error';
|
||||
@@ -292,7 +266,6 @@
|
||||
currentIndex = 0;
|
||||
summary = null;
|
||||
errorMessage = '';
|
||||
filterMode = 'updated';
|
||||
}
|
||||
|
||||
function handleOpenChange(isOpen: boolean) {
|
||||
@@ -411,18 +384,10 @@ const severityOrder: Record<string, number> = { critical: 0, high: 1, medium: 2,
|
||||
}
|
||||
});
|
||||
|
||||
// Track whether user has scrolled up to read earlier output
|
||||
function handleProgressScroll() {
|
||||
if (!progressListEl) return;
|
||||
const { scrollTop, scrollHeight, clientHeight } = progressListEl;
|
||||
// Consider "at bottom" if within 50px of the end
|
||||
userScrolledUp = scrollHeight - scrollTop - clientHeight > 50;
|
||||
}
|
||||
|
||||
// Auto-scroll progress list to bottom on SSE data, but only if user hasn't scrolled up
|
||||
// Auto-scroll progress list to bottom on SSE data (not UI toggles)
|
||||
$effect(() => {
|
||||
scrollTick;
|
||||
if (progressListEl && !userScrolledUp) {
|
||||
if (progressListEl) {
|
||||
requestAnimationFrame(() => {
|
||||
progressListEl?.scrollTo({ top: progressListEl.scrollHeight, behavior: 'smooth' });
|
||||
});
|
||||
@@ -473,33 +438,10 @@ const severityOrder: Record<string, number> = { critical: 0, high: 1, medium: 2,
|
||||
<Progress value={progressPercentage} class="h-2" />
|
||||
</div>
|
||||
|
||||
<!-- Filter toggle + Container list with status - scrollable area -->
|
||||
<!-- Container list with status - scrollable area -->
|
||||
{#if progress.length > 0}
|
||||
{#if summary && (summary.failed > 0 || summary.blocked > 0) && summary.success > 0}
|
||||
<div class="flex items-center gap-1 shrink-0">
|
||||
<Button
|
||||
variant={filterMode === 'updated' ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
class="h-7 text-xs"
|
||||
onclick={() => filterMode = 'updated'}
|
||||
>
|
||||
<CheckCircle2 class="w-3 h-3 mr-1" />
|
||||
Updated ({summary.success})
|
||||
</Button>
|
||||
<Button
|
||||
variant={filterMode === 'failed' ? 'destructive' : 'outline'}
|
||||
size="sm"
|
||||
class="h-7 text-xs"
|
||||
onclick={() => filterMode = 'failed'}
|
||||
>
|
||||
<XCircle class="w-3 h-3 mr-1" />
|
||||
Failed ({summary.failed + summary.blocked})
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div bind:this={progressListEl} onscroll={handleProgressScroll} class="border rounded-lg divide-y flex-1 min-h-0 overflow-auto">
|
||||
{#each filteredProgress as item (item.containerId)}
|
||||
<div bind:this={progressListEl} class="border rounded-lg divide-y flex-1 min-h-0 overflow-auto">
|
||||
{#each progress as item (item.containerId)}
|
||||
{@const StepIcon = getStepIcon(item.step)}
|
||||
{@const isActive = item.step !== 'done' && item.step !== 'failed' && item.step !== 'blocked'}
|
||||
{@const hasLogs = item.pullLogs.length > 0 || item.scanLogs.length > 0 || (item.vulnerabilities && item.vulnerabilities.length > 0)}
|
||||
|
||||
@@ -864,8 +864,6 @@
|
||||
retries: healthcheckRetries,
|
||||
startPeriod: healthcheckStartPeriod * 1e9
|
||||
};
|
||||
} else if (!healthcheckEnabled) {
|
||||
healthcheck = null;
|
||||
}
|
||||
|
||||
const devices = deviceMappings
|
||||
@@ -904,8 +902,8 @@
|
||||
const payload = {
|
||||
name: name.trim(),
|
||||
image: image.trim(),
|
||||
ports: Object.keys(ports).length > 0 ? ports : null,
|
||||
volumeBinds: volumeBinds.length > 0 ? volumeBinds : null,
|
||||
ports: Object.keys(ports).length > 0 ? ports : undefined,
|
||||
volumeBinds: volumeBinds.length > 0 ? volumeBinds : undefined,
|
||||
env: env.length > 0 ? env : undefined,
|
||||
labels: Object.keys(labelsObj).length > 0 ? labelsObj : undefined,
|
||||
cmd,
|
||||
@@ -1083,8 +1081,8 @@
|
||||
bind:restartPolicy
|
||||
bind:restartMaxRetries
|
||||
bind:networkMode
|
||||
bind:startAfterCreate={startAfterUpdate}
|
||||
bind:repullImage
|
||||
startAfterCreate={startAfterUpdate}
|
||||
{repullImage}
|
||||
bind:portMappings
|
||||
bind:volumeMappings
|
||||
bind:envVars
|
||||
|
||||
@@ -162,37 +162,20 @@
|
||||
// Push colliding items down (returns new array)
|
||||
function pushCollidingItems(movedItem: GridItemLayout, sourceItems: GridItemLayout[]): GridItemLayout[] {
|
||||
const newItems = sourceItems.map(item => ({ ...item }));
|
||||
|
||||
// Step 1: Push items that directly collide with the moved item
|
||||
for (const item of newItems) {
|
||||
if (item.id === movedItem.id) continue;
|
||||
const overlaps = !(item.x + item.w <= movedItem.x || item.x >= movedItem.x + movedItem.w ||
|
||||
item.y + item.h <= movedItem.y || item.y >= movedItem.y + movedItem.h);
|
||||
if (overlaps) {
|
||||
item.y = movedItem.y + movedItem.h;
|
||||
}
|
||||
}
|
||||
|
||||
// Step 2: Resolve cascading collisions by sorting top-to-bottom and pushing down
|
||||
let changed = true;
|
||||
let iterations = 0;
|
||||
while (changed && iterations < 100) {
|
||||
const maxIterations = 100; // Prevent infinite loops
|
||||
|
||||
while (changed && iterations < maxIterations) {
|
||||
changed = false;
|
||||
iterations++;
|
||||
const sorted = newItems
|
||||
.filter(i => i.id !== movedItem.id)
|
||||
.sort((a, b) => a.y - b.y || a.x - b.x);
|
||||
for (const item of newItems) {
|
||||
if (item.id === movedItem.id) continue;
|
||||
|
||||
for (let i = 0; i < sorted.length; i++) {
|
||||
for (let j = i + 1; j < sorted.length; j++) {
|
||||
const upper = sorted[i];
|
||||
const lower = sorted[j];
|
||||
const overlaps = !(upper.x + upper.w <= lower.x || upper.x >= lower.x + lower.w ||
|
||||
upper.y + upper.h <= lower.y || upper.y >= lower.y + lower.h);
|
||||
if (overlaps) {
|
||||
lower.y = upper.y + upper.h;
|
||||
changed = true;
|
||||
}
|
||||
if (hasCollision(item, movedItem)) {
|
||||
// Push this item down
|
||||
item.y = movedItem.y + movedItem.h;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,8 +241,8 @@
|
||||
{vuln.severity}
|
||||
</Badge>
|
||||
</td>
|
||||
<td class="py-1 px-2 max-w-[300px]">
|
||||
<code class="text-xs block truncate" title={vuln.package}>{vuln.package}</code>
|
||||
<td class="py-1 px-2">
|
||||
<code class="text-xs">{vuln.package}</code>
|
||||
</td>
|
||||
<td class="py-1 px-2">
|
||||
<code class="text-xs text-muted-foreground">{vuln.version}</code>
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
import { Loader2, LogIn, Shield, AlertCircle, Network, User, KeyRound, TriangleAlert } from 'lucide-svelte';
|
||||
import { authStore } from '$lib/stores/auth';
|
||||
import { environments } from '$lib/stores/environment';
|
||||
import { appSettings } from '$lib/stores/settings';
|
||||
import * as Alert from '$lib/components/ui/alert';
|
||||
import { themeStore, applyTheme } from '$lib/stores/theme';
|
||||
|
||||
@@ -115,8 +114,7 @@
|
||||
return;
|
||||
}
|
||||
|
||||
// Success - refresh settings and environments (they were fetched before auth) then redirect
|
||||
await appSettings.refresh();
|
||||
// Success - refresh environments (they were cleared during pre-login fetch) then redirect
|
||||
await environments.refresh();
|
||||
goto(redirectUrl);
|
||||
} catch (e) {
|
||||
@@ -291,7 +289,6 @@
|
||||
<Label for="mfaToken">Authentication code</Label>
|
||||
<Input
|
||||
id="mfaToken"
|
||||
name="totp"
|
||||
type="text"
|
||||
placeholder="Enter code"
|
||||
bind:value={mfaToken}
|
||||
|
||||
+31
-209
@@ -10,15 +10,13 @@
|
||||
import * as Select from '$lib/components/ui/select';
|
||||
import { Checkbox } from '$lib/components/ui/checkbox';
|
||||
import { ToggleGroup } from '$lib/components/ui/toggle-pill';
|
||||
import { RefreshCw, Search, ChevronDown, ChevronUp, Unplug, Copy, Download, WrapText, ArrowDownToLine, X, Sun, Moon, LayoutList, Square, Box, Wifi, WifiOff, Pause, Play, ScrollText, Star, GripVertical, Layers, Check, FolderHeart, Save, Trash2, MoreHorizontal, Eraser, Filter, GripHorizontal, Terminal, ArrowDown, ArrowRight } from 'lucide-svelte';
|
||||
import { RefreshCw, Search, ChevronDown, ChevronUp, Unplug, Copy, Download, WrapText, ArrowDownToLine, X, Sun, Moon, LayoutList, Square, Box, Wifi, WifiOff, Pause, Play, ScrollText, Star, GripVertical, Layers, Check, FolderHeart, Save, Trash2, MoreHorizontal, Eraser } from 'lucide-svelte';
|
||||
import { copyToClipboard } from '$lib/utils/clipboard';
|
||||
import PageHeader from '$lib/components/PageHeader.svelte';
|
||||
import TerminalPanel from '../terminal/TerminalPanel.svelte';
|
||||
import { detectShells, getBestShell, getSavedUser } from '$lib/utils/shell-detection';
|
||||
import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
import type { ContainerInfo } from '$lib/types';
|
||||
import { currentEnvironment, environments, appendEnvParam } from '$lib/stores/environment';
|
||||
import { appSettings, formatLogTimestamps } from '$lib/stores/settings';
|
||||
import { appSettings } from '$lib/stores/settings';
|
||||
import { NoEnvironment } from '$lib/components/ui/empty-state';
|
||||
import { AnsiUp } from 'ansi_up';
|
||||
const ansiUp = new AnsiUp();
|
||||
@@ -308,94 +306,12 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
// Log search state
|
||||
let logSearchActive = $state(false);
|
||||
let logSearchQuery = $state('');
|
||||
let logSearchFilterMode = $state(false);
|
||||
let currentMatchIndex = $state(0);
|
||||
let matchCount = $state(0);
|
||||
let logSearchInputRef: HTMLInputElement | undefined;
|
||||
|
||||
const fontSizeOptions = [10, 12, 14, 16];
|
||||
|
||||
// Terminal state
|
||||
let terminalOpen = $state(false);
|
||||
let terminalContainerId = $state<string | null>(null);
|
||||
let terminalContainerName = $state('');
|
||||
let terminalShell = $state('/bin/bash');
|
||||
let terminalUser = $state('root');
|
||||
let terminalLayout = $state<'below' | 'right'>('below');
|
||||
let terminalSplitRatio = $state(0.5); // 0-1, ratio of logs panel
|
||||
let isResizingTerminal = $state(false);
|
||||
let terminalSplitRef: HTMLDivElement | undefined;
|
||||
|
||||
const TERMINAL_LAYOUT_KEY = 'dockhand-logs-terminal-layout';
|
||||
const TERMINAL_SPLIT_KEY = 'dockhand-logs-terminal-split';
|
||||
|
||||
function loadTerminalSettings() {
|
||||
if (typeof window === 'undefined') return;
|
||||
const savedLayout = localStorage.getItem(TERMINAL_LAYOUT_KEY);
|
||||
if (savedLayout === 'below' || savedLayout === 'right') terminalLayout = savedLayout;
|
||||
const savedSplit = localStorage.getItem(TERMINAL_SPLIT_KEY);
|
||||
if (savedSplit) {
|
||||
const r = parseFloat(savedSplit);
|
||||
if (!isNaN(r) && r >= 0.2 && r <= 0.8) terminalSplitRatio = r;
|
||||
}
|
||||
}
|
||||
|
||||
function saveTerminalSettings() {
|
||||
if (typeof window === 'undefined') return;
|
||||
localStorage.setItem(TERMINAL_LAYOUT_KEY, terminalLayout);
|
||||
localStorage.setItem(TERMINAL_SPLIT_KEY, String(terminalSplitRatio));
|
||||
}
|
||||
|
||||
async function openTerminal(containerId: string, containerName: string, layout?: 'below' | 'right') {
|
||||
if (terminalOpen && terminalContainerId === containerId && (!layout || layout === terminalLayout)) {
|
||||
closeTerminal();
|
||||
return;
|
||||
}
|
||||
if (layout) {
|
||||
terminalLayout = layout;
|
||||
saveTerminalSettings();
|
||||
}
|
||||
terminalContainerId = containerId;
|
||||
terminalContainerName = containerName;
|
||||
const savedUser = getSavedUser(containerId);
|
||||
if (savedUser) terminalUser = savedUser;
|
||||
const result = await detectShells(containerId, envId);
|
||||
const best = getBestShell(result, terminalShell);
|
||||
if (best) terminalShell = best;
|
||||
terminalOpen = true;
|
||||
}
|
||||
|
||||
function closeTerminal() {
|
||||
terminalOpen = false;
|
||||
terminalContainerId = null;
|
||||
}
|
||||
|
||||
function startTerminalResize(e: MouseEvent) {
|
||||
e.preventDefault();
|
||||
isResizingTerminal = true;
|
||||
document.addEventListener('mousemove', handleTerminalResize);
|
||||
document.addEventListener('mouseup', stopTerminalResize);
|
||||
}
|
||||
|
||||
function handleTerminalResize(e: MouseEvent) {
|
||||
if (!isResizingTerminal || !terminalSplitRef) return;
|
||||
const rect = terminalSplitRef.getBoundingClientRect();
|
||||
let ratio: number;
|
||||
if (terminalLayout === 'below') {
|
||||
ratio = (e.clientY - rect.top) / rect.height;
|
||||
} else {
|
||||
ratio = (e.clientX - rect.left) / rect.width;
|
||||
}
|
||||
terminalSplitRatio = Math.max(0.2, Math.min(0.8, ratio));
|
||||
}
|
||||
|
||||
function stopTerminalResize() {
|
||||
isResizingTerminal = false;
|
||||
document.removeEventListener('mousemove', handleTerminalResize);
|
||||
document.removeEventListener('mouseup', stopTerminalResize);
|
||||
saveTerminalSettings();
|
||||
}
|
||||
|
||||
// Subscribe to environment changes - restore state and fetch data
|
||||
const unsubscribeEnv = currentEnvironment.subscribe(async (env) => {
|
||||
envId = env?.id ?? null;
|
||||
@@ -853,10 +769,6 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
return `[${data.containerName}] ${line}`;
|
||||
}).join('\n');
|
||||
}
|
||||
// Format timestamps if enabled
|
||||
if ($appSettings.formatLogTimestamps) {
|
||||
text = formatLogTimestamps(text);
|
||||
}
|
||||
// Buffer text and schedule flush
|
||||
pendingText += text;
|
||||
if (!flushTimer) {
|
||||
@@ -1041,13 +953,12 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
if (data.text) {
|
||||
// Use consistent color based on position in all selected containers
|
||||
const color = getContainerColor(data.containerId);
|
||||
const logText = $appSettings.formatLogTimestamps ? formatLogTimestamps(data.text) : data.text;
|
||||
// Add to pending batch instead of updating state immediately
|
||||
pendingLogs.push({
|
||||
containerId: data.containerId,
|
||||
containerName: data.containerName,
|
||||
color,
|
||||
text: logText,
|
||||
text: data.text,
|
||||
timestamp: data.timestamp,
|
||||
stream: data.stream
|
||||
});
|
||||
@@ -1223,11 +1134,6 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
// Stop any existing stream
|
||||
stopStreaming();
|
||||
|
||||
// Close terminal when switching containers
|
||||
if (terminalOpen && terminalContainerId !== container.id) {
|
||||
closeTerminal();
|
||||
}
|
||||
|
||||
selectedContainer = container;
|
||||
searchQuery = '';
|
||||
dropdownOpen = false;
|
||||
@@ -1408,15 +1314,10 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
function closeLogSearch() {
|
||||
logSearchActive = false;
|
||||
logSearchQuery = '';
|
||||
logSearchFilterMode = false;
|
||||
currentMatchIndex = 0;
|
||||
matchCount = 0;
|
||||
}
|
||||
|
||||
function toggleSearchFilterMode() {
|
||||
logSearchFilterMode = !logSearchFilterMode;
|
||||
}
|
||||
|
||||
function navigateMatch(direction: 'prev' | 'next') {
|
||||
if (!logsRef || matchCount === 0) return;
|
||||
|
||||
@@ -1467,54 +1368,38 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
|
||||
// Highlighted logs with search matches and ANSI color support (single container mode)
|
||||
let highlightedLogs = $derived(() => {
|
||||
let text = logs || '';
|
||||
const query = logSearchQuery.trim();
|
||||
// First convert ANSI codes to HTML
|
||||
const withAnsi = ansiToHtml(logs || '');
|
||||
if (!logSearchQuery.trim()) return withAnsi;
|
||||
|
||||
// Filter lines before ANSI conversion (plain text matching)
|
||||
if (logSearchFilterMode && query) {
|
||||
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const filterRegex = new RegExp(escapedForRegex, 'i');
|
||||
text = text.split('\n').filter(line => filterRegex.test(line)).join('\n');
|
||||
}
|
||||
|
||||
const withAnsi = ansiToHtml(text);
|
||||
if (!query) return withAnsi;
|
||||
|
||||
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const escapedQuery = escapeHtml(escapedForRegex);
|
||||
// For search, we need to highlight matches while preserving HTML tags
|
||||
// We'll only highlight text outside of HTML tags
|
||||
const query = logSearchQuery.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const escapedQuery = escapeHtml(query);
|
||||
|
||||
// Split by HTML tags and only process text parts
|
||||
const parts = withAnsi.split(/(<[^>]*>)/);
|
||||
return parts.map(part => {
|
||||
const highlighted = parts.map(part => {
|
||||
// Skip HTML tags
|
||||
if (part.startsWith('<')) return part;
|
||||
// Highlight matches in text
|
||||
const regex = new RegExp(`(${escapedQuery})`, 'gi');
|
||||
return part.replace(regex, '<mark class="search-match">$1</mark>');
|
||||
}).join('');
|
||||
|
||||
return highlighted;
|
||||
});
|
||||
|
||||
// Format merged logs HTML — uses pre-built mergedHtml string, only applies search highlighting when needed
|
||||
let formattedMergedHtml = $derived(() => {
|
||||
if (!mergedHtml) return '';
|
||||
const query = logSearchQuery.trim();
|
||||
if (!logSearchQuery.trim()) return mergedHtml;
|
||||
|
||||
// Filter mode: remove non-matching lines from HTML
|
||||
let html = mergedHtml;
|
||||
if (logSearchFilterMode && query) {
|
||||
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const filterRegex = new RegExp(escapedForRegex, 'i');
|
||||
// Split by <br/> or newlines, filter lines (strip HTML for matching, keep original for display)
|
||||
const lines = html.split(/\n/);
|
||||
html = lines.filter(line => {
|
||||
const plainText = line.replace(/<[^>]*>/g, '');
|
||||
return filterRegex.test(plainText);
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
if (!query) return html;
|
||||
|
||||
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const escapedQuery = escapeHtml(escapedForRegex);
|
||||
// Apply search highlighting (same approach as single mode's highlightedLogs)
|
||||
const query = logSearchQuery.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const escapedQuery = escapeHtml(query);
|
||||
const searchRegex = new RegExp(`(${escapedQuery})`, 'gi');
|
||||
const parts = html.split(/(<[^>]*>)/);
|
||||
const parts = mergedHtml.split(/(<[^>]*>)/);
|
||||
return parts.map(part => {
|
||||
if (part.startsWith('<')) return part;
|
||||
return part.replace(searchRegex, '<mark class="search-match">$1</mark>');
|
||||
@@ -1545,7 +1430,6 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
|
||||
|
||||
onMount(() => {
|
||||
loadTerminalSettings();
|
||||
// All initialization is handled in currentEnvironment.subscribe
|
||||
// This just sets up the refresh interval
|
||||
containerInterval = setInterval(fetchContainers, 10000);
|
||||
@@ -1553,8 +1437,6 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
document.removeEventListener('mousemove', handleTerminalResize);
|
||||
document.removeEventListener('mouseup', stopTerminalResize);
|
||||
unsubscribeEnv();
|
||||
if (containerInterval) {
|
||||
clearInterval(containerInterval);
|
||||
@@ -1949,9 +1831,8 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Logs + Terminal split -->
|
||||
<div bind:this={terminalSplitRef} class="flex-1 min-h-0 min-w-0 overflow-hidden flex {terminalOpen ? (terminalLayout === 'below' ? 'flex-col' : 'flex-row') : ''} gap-0">
|
||||
<div class="{terminalOpen ? 'min-h-0 min-w-0' : 'flex-1'} border rounded-lg overflow-hidden flex flex-col transition-colors {darkMode ? 'bg-zinc-950 border-zinc-800' : 'bg-gray-50 border-gray-300'}" style="{terminalOpen ? (terminalLayout === 'below' ? `height: ${terminalSplitRatio * 100}%` : `width: ${terminalSplitRatio * 100}%`) : ''}">
|
||||
<!-- Logs panel -->
|
||||
<div class="flex-1 min-h-0 border rounded-lg overflow-hidden flex flex-col transition-colors {darkMode ? 'bg-zinc-950 border-zinc-800' : 'bg-gray-50 border-gray-300'}">
|
||||
{#if layoutMode === 'grouped'}
|
||||
{#if selectedContainerIds.size === 0}
|
||||
<div class="flex items-center justify-center h-full text-muted-foreground">
|
||||
@@ -1959,8 +1840,8 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Header bar for grouped mode -->
|
||||
<div class="flex items-center flex-wrap gap-y-1 px-3 py-1.5 border-b shrink-0 transition-colors {darkMode ? 'border-zinc-800 bg-zinc-900/50' : 'border-gray-300 bg-gray-100'}">
|
||||
<div class="flex items-center gap-2 shrink-0">
|
||||
<div class="flex items-center justify-between px-3 py-1.5 border-b shrink-0 transition-colors {darkMode ? 'border-zinc-800 bg-zinc-900/50' : 'border-gray-300 bg-gray-100'}">
|
||||
<div class="flex items-center gap-2 min-w-[100px]">
|
||||
{#if streamingEnabled}
|
||||
{#if isConnected}
|
||||
<div class="flex items-center gap-1.5" title="Connected - Live streaming">
|
||||
@@ -2004,7 +1885,7 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 flex-wrap ml-auto">
|
||||
<div class="flex items-center gap-3">
|
||||
<button
|
||||
onclick={toggleStreaming}
|
||||
class="flex items-center gap-1.5 px-2 py-1 rounded text-xs transition-colors {streamingEnabled ? (darkMode ? 'bg-amber-500/20 ring-1 ring-amber-500/50 text-amber-400' : 'bg-amber-500/30 ring-1 ring-amber-600/50 text-amber-700') : darkMode ? 'text-zinc-500 hover:text-zinc-300 hover:bg-zinc-800' : 'text-gray-500 hover:text-gray-700 hover:bg-gray-200'}"
|
||||
@@ -2062,13 +1943,6 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
onkeydown={handleLogSearchKeydown}
|
||||
class="bg-transparent border-none outline-none text-xs w-28 {darkMode ? 'text-zinc-200 placeholder:text-zinc-500' : 'text-gray-800 placeholder:text-gray-400'}"
|
||||
/>
|
||||
<button
|
||||
onclick={toggleSearchFilterMode}
|
||||
class="p-0.5 rounded transition-colors {logSearchFilterMode ? (darkMode ? 'bg-amber-500/20 ring-1 ring-amber-500/50' : 'bg-amber-500/30 ring-1 ring-amber-600/50') : darkMode ? 'hover:bg-zinc-700' : 'hover:bg-gray-300'}"
|
||||
title={logSearchFilterMode ? 'Show all lines (filter mode active)' : 'Hide non-matching lines'}
|
||||
>
|
||||
<Filter class="w-3 h-3 transition-colors {logSearchFilterMode ? (darkMode ? 'text-amber-400' : 'text-amber-700') : darkMode ? 'text-zinc-400' : 'text-gray-500'}" />
|
||||
</button>
|
||||
{#if matchCount > 0}
|
||||
<span class="text-xs {darkMode ? 'text-zinc-400' : 'text-gray-500'}">{currentMatchIndex + 1}/{matchCount}</span>
|
||||
{:else if logSearchQuery}
|
||||
@@ -2119,8 +1993,8 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Header bar inside black area -->
|
||||
<div class="flex items-center flex-wrap gap-y-1 px-3 py-1.5 border-b shrink-0 transition-colors {darkMode ? 'border-zinc-800 bg-zinc-900/50' : 'border-gray-300 bg-gray-100'}">
|
||||
<div class="flex items-center gap-2 shrink-0">
|
||||
<div class="flex items-center justify-between px-3 py-1.5 border-b shrink-0 transition-colors {darkMode ? 'border-zinc-800 bg-zinc-900/50' : 'border-gray-300 bg-gray-100'}">
|
||||
<div class="flex items-center gap-2 min-w-[100px]">
|
||||
<!-- Connection status indicator -->
|
||||
{#if streamingEnabled}
|
||||
{#if isConnected}
|
||||
@@ -2154,34 +2028,14 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
<span class="text-xs {darkMode ? 'text-zinc-500' : 'text-gray-400'}">Paused</span>
|
||||
</div>
|
||||
{/if}
|
||||
<!-- Container name + terminal toggles -->
|
||||
<!-- Container name -->
|
||||
{#if selectedContainer}
|
||||
<div class="flex items-center gap-1.5 ml-2">
|
||||
<div class="flex items-center gap-1 ml-2">
|
||||
<span class="text-xs font-medium {darkMode ? 'text-zinc-300' : 'text-gray-700'}">{selectedContainer.name}</span>
|
||||
<button
|
||||
onclick={() => openTerminal(selectedContainer!.id, selectedContainer!.name, 'below')}
|
||||
class="p-0.5 rounded transition-colors {terminalOpen && terminalLayout === 'below' && terminalContainerId === selectedContainer.id ? (darkMode ? 'bg-amber-500/20 ring-1 ring-amber-500/50' : 'bg-amber-500/30 ring-1 ring-amber-600/50') : darkMode ? 'hover:bg-zinc-800' : 'hover:bg-gray-200'}"
|
||||
title="Terminal below"
|
||||
>
|
||||
<span class="inline-flex items-center gap-px">
|
||||
<Terminal class="w-3.5 h-3.5 {terminalOpen && terminalLayout === 'below' && terminalContainerId === selectedContainer.id ? (darkMode ? 'text-amber-400' : 'text-amber-700') : darkMode ? 'text-zinc-500 hover:text-zinc-300' : 'text-gray-500 hover:text-gray-700'}" />
|
||||
<ArrowDown class="w-2.5 h-2.5 {terminalOpen && terminalLayout === 'below' && terminalContainerId === selectedContainer.id ? (darkMode ? 'text-amber-400' : 'text-amber-700') : darkMode ? 'text-zinc-600' : 'text-gray-400'}" strokeWidth={2.5} />
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
onclick={() => openTerminal(selectedContainer!.id, selectedContainer!.name, 'right')}
|
||||
class="p-0.5 rounded transition-colors {terminalOpen && terminalLayout === 'right' && terminalContainerId === selectedContainer.id ? (darkMode ? 'bg-amber-500/20 ring-1 ring-amber-500/50' : 'bg-amber-500/30 ring-1 ring-amber-600/50') : darkMode ? 'hover:bg-zinc-800' : 'hover:bg-gray-200'}"
|
||||
title="Terminal on side"
|
||||
>
|
||||
<span class="inline-flex items-center gap-px">
|
||||
<Terminal class="w-3.5 h-3.5 {terminalOpen && terminalLayout === 'right' && terminalContainerId === selectedContainer.id ? (darkMode ? 'text-amber-400' : 'text-amber-700') : darkMode ? 'text-zinc-500 hover:text-zinc-300' : 'text-gray-500 hover:text-gray-700'}" />
|
||||
<ArrowRight class="w-2.5 h-2.5 {terminalOpen && terminalLayout === 'right' && terminalContainerId === selectedContainer.id ? (darkMode ? 'text-amber-400' : 'text-amber-700') : darkMode ? 'text-zinc-600' : 'text-gray-400'}" strokeWidth={2.5} />
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="flex items-center gap-2 flex-wrap ml-auto">
|
||||
<div class="flex items-center gap-3">
|
||||
<!-- Streaming toggle -->
|
||||
<button
|
||||
onclick={toggleStreaming}
|
||||
@@ -2245,13 +2099,6 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
onkeydown={handleLogSearchKeydown}
|
||||
class="bg-transparent border-none outline-none text-xs w-28 {darkMode ? 'text-zinc-200 placeholder:text-zinc-500' : 'text-gray-800 placeholder:text-gray-400'}"
|
||||
/>
|
||||
<button
|
||||
onclick={toggleSearchFilterMode}
|
||||
class="p-0.5 rounded transition-colors {logSearchFilterMode ? (darkMode ? 'bg-amber-500/20 ring-1 ring-amber-500/50' : 'bg-amber-500/30 ring-1 ring-amber-600/50') : darkMode ? 'hover:bg-zinc-700' : 'hover:bg-gray-300'}"
|
||||
title={logSearchFilterMode ? 'Show all lines (filter mode active)' : 'Hide non-matching lines'}
|
||||
>
|
||||
<Filter class="w-3 h-3 transition-colors {logSearchFilterMode ? (darkMode ? 'text-amber-400' : 'text-amber-700') : darkMode ? 'text-zinc-400' : 'text-gray-500'}" />
|
||||
</button>
|
||||
{#if matchCount > 0}
|
||||
<span class="text-xs {darkMode ? 'text-zinc-400' : 'text-gray-500'}">{currentMatchIndex + 1}/{matchCount}</span>
|
||||
{:else if logSearchQuery}
|
||||
@@ -2330,31 +2177,6 @@ import type { FavoriteGroup } from '../api/preferences/favorite-groups/+server';
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
<!-- Terminal panel with resize handle -->
|
||||
{#if terminalOpen && terminalContainerId}
|
||||
<!-- Resize handle -->
|
||||
<div
|
||||
role="separator"
|
||||
class="{terminalLayout === 'below' ? 'h-2 cursor-ns-resize w-full' : 'w-2 cursor-ew-resize h-full'} flex items-center justify-center hover:bg-muted/50 transition-colors {isResizingTerminal ? 'bg-muted/50' : ''}"
|
||||
onmousedown={startTerminalResize}
|
||||
>
|
||||
<GripHorizontal class="{terminalLayout === 'below' ? 'w-8 h-4' : 'w-4 h-8 rotate-90'} text-zinc-600" />
|
||||
</div>
|
||||
<!-- Terminal -->
|
||||
<div class="min-h-0 min-w-0 border rounded-lg overflow-hidden" style="{terminalLayout === 'below' ? `height: ${(1 - terminalSplitRatio) * 100}%` : `width: ${(1 - terminalSplitRatio) * 100}%`}">
|
||||
<TerminalPanel
|
||||
containerId={terminalContainerId}
|
||||
containerName={terminalContainerName}
|
||||
shell={terminalShell}
|
||||
user={terminalUser}
|
||||
visible={true}
|
||||
envId={envId}
|
||||
fillHeight={true}
|
||||
onClose={closeTerminal}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { RefreshCw, Copy, Download, WrapText, ArrowDownToLine, Search, ChevronUp, ChevronDown, X, Type, Eraser, Filter } from 'lucide-svelte';
|
||||
import { RefreshCw, Copy, Download, WrapText, ArrowDownToLine, Search, ChevronUp, ChevronDown, X, Type, Eraser } from 'lucide-svelte';
|
||||
import { copyToClipboard } from '$lib/utils/clipboard';
|
||||
import * as Select from '$lib/components/ui/select';
|
||||
import { appSettings, formatLogTimestamps } from '$lib/stores/settings';
|
||||
@@ -45,7 +45,6 @@
|
||||
// Search state
|
||||
let logSearchActive = $state(false);
|
||||
let logSearchQuery = $state('');
|
||||
let logSearchFilterMode = $state(typeof window !== 'undefined' && localStorage.getItem('dockhand-log-filter-mode') === 'true');
|
||||
let currentMatchIndex = $state(0);
|
||||
let matchCount = $state(0);
|
||||
let logSearchInputRef: HTMLInputElement;
|
||||
@@ -108,16 +107,10 @@
|
||||
function closeLogSearch() {
|
||||
logSearchActive = false;
|
||||
logSearchQuery = '';
|
||||
logSearchFilterMode = false;
|
||||
currentMatchIndex = 0;
|
||||
matchCount = 0;
|
||||
}
|
||||
|
||||
function toggleSearchFilterMode() {
|
||||
logSearchFilterMode = !logSearchFilterMode;
|
||||
localStorage.setItem('dockhand-log-filter-mode', String(logSearchFilterMode));
|
||||
}
|
||||
|
||||
function navigateMatch(direction: 'prev' | 'next') {
|
||||
if (!logsRef || matchCount === 0) return;
|
||||
|
||||
@@ -158,22 +151,11 @@
|
||||
if ($appSettings.formatLogTimestamps) {
|
||||
text = formatLogTimestamps(text);
|
||||
}
|
||||
|
||||
const query = logSearchQuery.trim();
|
||||
|
||||
// Filter lines before ANSI conversion (plain text matching)
|
||||
if (logSearchFilterMode && query) {
|
||||
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const filterRegex = new RegExp(escapedForRegex, 'i');
|
||||
const lines = text.split('\n');
|
||||
text = lines.filter(line => filterRegex.test(line)).join('\n');
|
||||
}
|
||||
|
||||
const withAnsi = ansiUp.ansi_to_html(text);
|
||||
if (!query) return withAnsi;
|
||||
if (!logSearchQuery.trim()) return withAnsi;
|
||||
|
||||
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const escapedQuery = escapedForRegex.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const query = logSearchQuery.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const escapedQuery = query.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
|
||||
// Split by HTML tags and only process text parts
|
||||
const parts = withAnsi.split(/(<[^>]*>)/);
|
||||
@@ -264,13 +246,6 @@
|
||||
onkeydown={handleLogSearchKeydown}
|
||||
class="bg-transparent border-none outline-none text-xs text-zinc-200 w-20 placeholder:text-zinc-500"
|
||||
/>
|
||||
<button
|
||||
onclick={toggleSearchFilterMode}
|
||||
class="p-0.5 rounded transition-colors {logSearchFilterMode ? 'bg-amber-500/20 ring-1 ring-amber-500/50' : 'hover:bg-zinc-700'}"
|
||||
title={logSearchFilterMode ? 'Show all lines (filter mode active)' : 'Hide non-matching lines'}
|
||||
>
|
||||
<Filter class="w-3 h-3 transition-colors {logSearchFilterMode ? 'text-amber-400' : 'text-zinc-400'}" />
|
||||
</button>
|
||||
{#if matchCount > 0}
|
||||
<span class="text-xs text-zinc-400">{currentMatchIndex + 1}/{matchCount}</span>
|
||||
{:else if logSearchQuery}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy, tick } from 'svelte';
|
||||
import { X, GripHorizontal, RefreshCw, Copy, Download, WrapText, ArrowDownToLine, Search, ChevronUp, ChevronDown, Sun, Moon, Wifi, WifiOff, Pause, Play, Eraser, Filter } from 'lucide-svelte';
|
||||
import { X, GripHorizontal, RefreshCw, Copy, Download, WrapText, ArrowDownToLine, Search, ChevronUp, ChevronDown, Sun, Moon, Wifi, WifiOff, Pause, Play, Eraser } from 'lucide-svelte';
|
||||
import { copyToClipboard } from '$lib/utils/clipboard';
|
||||
import * as Select from '$lib/components/ui/select';
|
||||
import { appSettings, formatLogTimestamps } from '$lib/stores/settings';
|
||||
@@ -53,7 +53,6 @@
|
||||
// Search state
|
||||
let logSearchActive = $state(false);
|
||||
let logSearchQuery = $state('');
|
||||
let logSearchFilterMode = $state(false);
|
||||
let currentMatchIndex = $state(0);
|
||||
let matchCount = $state(0);
|
||||
let logSearchInputRef: HTMLInputElement | undefined;
|
||||
@@ -98,7 +97,6 @@
|
||||
if (settings.fontSize !== undefined) fontSize = settings.fontSize;
|
||||
if (settings.autoScroll !== undefined) autoScroll = settings.autoScroll;
|
||||
if (settings.streamingEnabled !== undefined) streamingEnabled = settings.streamingEnabled;
|
||||
if (settings.logSearchFilterMode !== undefined) logSearchFilterMode = settings.logSearchFilterMode;
|
||||
} catch {
|
||||
// Ignore parse errors
|
||||
}
|
||||
@@ -114,8 +112,7 @@
|
||||
wordWrap,
|
||||
fontSize,
|
||||
autoScroll,
|
||||
streamingEnabled,
|
||||
logSearchFilterMode
|
||||
streamingEnabled
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -493,16 +490,10 @@
|
||||
function closeLogSearch() {
|
||||
logSearchActive = false;
|
||||
logSearchQuery = '';
|
||||
logSearchFilterMode = false;
|
||||
currentMatchIndex = 0;
|
||||
matchCount = 0;
|
||||
}
|
||||
|
||||
function toggleSearchFilterMode() {
|
||||
logSearchFilterMode = !logSearchFilterMode;
|
||||
saveSettings();
|
||||
}
|
||||
|
||||
function navigateMatch(direction: 'prev' | 'next') {
|
||||
if (!logsRef || matchCount === 0) return;
|
||||
|
||||
@@ -543,22 +534,11 @@
|
||||
if ($appSettings.formatLogTimestamps) {
|
||||
text = formatLogTimestamps(text);
|
||||
}
|
||||
|
||||
const query = logSearchQuery.trim();
|
||||
|
||||
// Filter lines before ANSI conversion (plain text matching)
|
||||
if (logSearchFilterMode && query) {
|
||||
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const filterRegex = new RegExp(escapedForRegex, 'i');
|
||||
const lines = text.split('\n');
|
||||
text = lines.filter(line => filterRegex.test(line)).join('\n');
|
||||
}
|
||||
|
||||
const withAnsi = ansiUp.ansi_to_html(text);
|
||||
if (!query) return withAnsi;
|
||||
if (!logSearchQuery.trim()) return withAnsi;
|
||||
|
||||
const escapedForRegex = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const escapedQuery = escapedForRegex.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const query = logSearchQuery.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const escapedQuery = query.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
|
||||
// Split by HTML tags and only process text parts
|
||||
const parts = withAnsi.split(/(<[^>]*>)/);
|
||||
@@ -754,13 +734,6 @@
|
||||
onkeydown={handleLogSearchKeydown}
|
||||
class="bg-transparent border-none outline-none text-xs w-20 {darkMode ? 'text-zinc-200 placeholder:text-zinc-500' : 'text-gray-800 placeholder:text-gray-400'}"
|
||||
/>
|
||||
<button
|
||||
onclick={toggleSearchFilterMode}
|
||||
class="p-0.5 rounded transition-colors {logSearchFilterMode ? (darkMode ? 'bg-amber-500/20 ring-1 ring-amber-500/50' : 'bg-amber-500/30 ring-1 ring-amber-600/50') : darkMode ? 'hover:bg-zinc-700' : 'hover:bg-gray-300'}"
|
||||
title={logSearchFilterMode ? 'Show all lines (filter mode active)' : 'Hide non-matching lines'}
|
||||
>
|
||||
<Filter class="w-3 h-3 transition-colors {logSearchFilterMode ? (darkMode ? 'text-amber-400' : 'text-amber-700') : darkMode ? 'text-zinc-400' : 'text-gray-500'}" />
|
||||
</button>
|
||||
{#if matchCount > 0}
|
||||
<span class="text-xs {darkMode ? 'text-zinc-400' : 'text-gray-500'}">{currentMatchIndex + 1}/{matchCount}</span>
|
||||
{:else if logSearchQuery}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import MultiSelectFilter from '$lib/components/MultiSelectFilter.svelte';
|
||||
import { Trash2, Search, Plus, Eye, Check, XCircle, RefreshCw, Icon, AlertTriangle, X, Network, Link, Copy, CopyPlus, Share2, Server, Globe, MonitorSmartphone, Cpu, CircleOff, GitGraph } from 'lucide-svelte';
|
||||
import { Trash2, Search, Plus, Eye, Check, XCircle, RefreshCw, Icon, AlertTriangle, X, Network, Link, Copy, CopyPlus, Share2, Server, Globe, MonitorSmartphone, Cpu, CircleOff } from 'lucide-svelte';
|
||||
import { broom } from '@lucide/lab';
|
||||
import { copyToClipboard } from '$lib/utils/clipboard';
|
||||
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
|
||||
@@ -25,7 +25,6 @@
|
||||
import PageHeader from '$lib/components/PageHeader.svelte';
|
||||
import { DataGrid } from '$lib/components/data-grid';
|
||||
import { ipToNumber } from '$lib/utils/ip';
|
||||
import NetworkGraphModal from './NetworkGraphModal.svelte';
|
||||
|
||||
type SortField = 'name' | 'driver' | 'containers' | 'subnet' | 'gateway';
|
||||
type SortDirection = 'asc' | 'desc';
|
||||
@@ -84,7 +83,6 @@
|
||||
let showCreateModal = $state(false);
|
||||
let showInspectModal = $state(false);
|
||||
let showConnectModal = $state(false);
|
||||
let showGraphModal = $state(false);
|
||||
let inspectNetworkId = $state('');
|
||||
let inspectNetworkName = $state('');
|
||||
let connectNetwork = $state<NetworkInfo | null>(null);
|
||||
@@ -353,10 +351,6 @@
|
||||
showConnectModal = true;
|
||||
}
|
||||
|
||||
function openGraphModal() {
|
||||
showGraphModal = true;
|
||||
}
|
||||
|
||||
async function disconnectContainer(networkId: string, networkName: string, containerId: string, containerName: string) {
|
||||
disconnectingContainerId = containerId;
|
||||
try {
|
||||
@@ -560,12 +554,8 @@
|
||||
<RefreshCw class="w-3.5 h-3.5" />
|
||||
Refresh
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onclick={openGraphModal}>
|
||||
<GitGraph class="w-3.5 h-3.5" />
|
||||
View Graph
|
||||
</Button>
|
||||
{#if $canAccess('networks', 'create')}
|
||||
<Button size="sm" variant="outline" onclick={() => showCreateModal = true}>
|
||||
<Button size="sm" variant="secondary" onclick={() => showCreateModal = true}>
|
||||
<Plus class="w-3.5 h-3.5" />
|
||||
Create
|
||||
</Button>
|
||||
@@ -752,12 +742,3 @@
|
||||
onClose={() => showBatchOpModal = false}
|
||||
onComplete={handleBatchComplete}
|
||||
/>
|
||||
|
||||
<!-- Edit Stack Modal -->
|
||||
<NetworkGraphModal
|
||||
bind:open={showGraphModal}
|
||||
networks={networks}
|
||||
onClose={() => {
|
||||
showGraphModal = false;
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from "svelte";
|
||||
import * as Dialog from "$lib/components/ui/dialog";
|
||||
import CodeEditor from "$lib/components/CodeEditor.svelte";
|
||||
import { Layers, X } from "lucide-svelte";
|
||||
import { focusFirstInput } from "$lib/utils";
|
||||
import { ErrorDialog } from "$lib/components/ui/error-dialog";
|
||||
import NetworkGraphViewer from "./NetworkGraphViewer.svelte";
|
||||
import { useSidebar } from "$lib/components/ui/sidebar/context.svelte";
|
||||
import type { NetworkInfo } from "$lib/types";
|
||||
|
||||
// Get sidebar state to adjust modal positioning
|
||||
const sidebar = useSidebar();
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
networks: NetworkInfo[]; // Required for edit mode, optional for create
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
let { open = $bindable(), networks: propNetworks, onClose }: Props = $props();
|
||||
|
||||
let networks = $state<NetworkInfo[]>([]);
|
||||
|
||||
// Form state
|
||||
let saving = $state(false);
|
||||
let editorTheme = $state<"light" | "dark">("dark");
|
||||
|
||||
// Error dialog state
|
||||
let operationError = $state<{
|
||||
title: string;
|
||||
message: string;
|
||||
details?: string;
|
||||
} | null>(null);
|
||||
|
||||
// CodeEditor reference for explicit marker updates
|
||||
let codeEditorRef: CodeEditor | null = $state(null);
|
||||
|
||||
// NetworkGraphViewer reference for resize on panel toggle
|
||||
let graphViewerRef: NetworkGraphViewer | null = $state(null);
|
||||
|
||||
// Display title
|
||||
const displayName = "DEMO";
|
||||
|
||||
onMount(() => {
|
||||
// Load saved editor theme, or fall back to app theme / system preference
|
||||
const savedEditorTheme = localStorage.getItem("dockhand-editor-theme");
|
||||
if (savedEditorTheme === "dark" || savedEditorTheme === "light") {
|
||||
editorTheme = savedEditorTheme;
|
||||
} else {
|
||||
const appTheme = localStorage.getItem("theme");
|
||||
if (appTheme === "dark" || appTheme === "light") {
|
||||
editorTheme = appTheme;
|
||||
} else {
|
||||
// Fallback to system preference
|
||||
editorTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function tryClose() {
|
||||
handleClose();
|
||||
}
|
||||
|
||||
let containerRef: HTMLDivElement | null = $state(null);
|
||||
|
||||
function handleClose() {
|
||||
// Reset mode back to prop values
|
||||
networks = propNetworks;
|
||||
codeEditorRef = null;
|
||||
operationError = null;
|
||||
onClose();
|
||||
}
|
||||
|
||||
// Initialize when dialog opens - ONLY ONCE per open
|
||||
let hasInitialized = $state(false);
|
||||
$effect(() => {
|
||||
if (open && !hasInitialized) {
|
||||
hasInitialized = true;
|
||||
// Reset mode to prop values on each open
|
||||
networks = propNetworks;
|
||||
} else if (!open) {
|
||||
hasInitialized = false; // Reset when modal closes
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<Dialog.Root
|
||||
bind:open
|
||||
onOpenChange={(isOpen) => {
|
||||
if (isOpen) {
|
||||
focusFirstInput();
|
||||
} else {
|
||||
// No unsaved changes - reset state
|
||||
handleClose();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Dialog.Content
|
||||
class="max-w-none h-[95vh] flex flex-col p-0 gap-0 shadow-xl border-zinc-200 dark:border-zinc-700 {sidebar.state === 'collapsed'
|
||||
? 'w-[calc(100vw-6rem)] ml-[1.5rem]'
|
||||
: 'w-[calc(100vw-12rem)] ml-[4.5rem]'}"
|
||||
showCloseButton={false}
|
||||
>
|
||||
<Dialog.Header class="px-5 py-3 border-b border-zinc-200 dark:border-zinc-700 flex-shrink-0">
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="p-1.5 rounded-md bg-zinc-200 dark:bg-zinc-700">
|
||||
<Layers class="w-4 h-4 text-zinc-600 dark:text-zinc-300" />
|
||||
</div>
|
||||
<div>
|
||||
<Dialog.Title class="text-sm font-semibold text-zinc-800 dark:text-zinc-100">View network graph</Dialog.Title>
|
||||
<Dialog.Description class="text-xs text-zinc-500 dark:text-zinc-400">View network connections between containers</Dialog.Description>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<!-- Close button -->
|
||||
<button
|
||||
onclick={tryClose}
|
||||
class="p-1.5 rounded-md text-zinc-400 dark:text-zinc-500 hover:text-zinc-600 dark:hover:text-zinc-300 hover:bg-zinc-200 dark:hover:bg-zinc-700 transition-colors"
|
||||
>
|
||||
<X class="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog.Header>
|
||||
|
||||
<!-- Content area -->
|
||||
<div bind:this={containerRef} class="flex-1 min-h-0 flex flex-col">
|
||||
<!-- Graph tab: Full width -->
|
||||
<NetworkGraphViewer bind:this={graphViewerRef} {networks} class="h-full flex-1" />
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<div class="px-5 py-2.5 border-t border-zinc-200 dark:border-zinc-700 flex items-center justify-between flex-shrink-0" />
|
||||
</Dialog.Content>
|
||||
</Dialog.Root>
|
||||
|
||||
<!-- Error dialog for failed operations -->
|
||||
{#if operationError}
|
||||
{@const errorDialogOpen = true}
|
||||
<ErrorDialog open={errorDialogOpen} title={operationError.title} message={operationError.message} details={operationError.details} onClose={() => (operationError = null)} />
|
||||
{/if}
|
||||
@@ -1,832 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from "svelte";
|
||||
import cytoscape from "cytoscape";
|
||||
import {
|
||||
Box,
|
||||
Database,
|
||||
Network,
|
||||
ZoomIn,
|
||||
ZoomOut,
|
||||
Maximize2,
|
||||
RotateCcw,
|
||||
X,
|
||||
ChevronDown,
|
||||
Sun,
|
||||
Moon,
|
||||
LayoutGrid,
|
||||
GitBranch,
|
||||
Circle,
|
||||
Target,
|
||||
Sparkles,
|
||||
Share2,
|
||||
Server,
|
||||
Globe,
|
||||
MonitorSmartphone,
|
||||
Cpu,
|
||||
CircleOff,
|
||||
} from "lucide-svelte";
|
||||
import { Button } from "$lib/components/ui/button";
|
||||
import { Input } from "$lib/components/ui/input";
|
||||
import type { NetworkInfo } from "$lib/types";
|
||||
|
||||
interface Props {
|
||||
networks: NetworkInfo[];
|
||||
class?: string;
|
||||
}
|
||||
|
||||
let { networks, class: className = "" }: Props = $props();
|
||||
|
||||
let containerEl: HTMLDivElement | null = $state(null);
|
||||
let cy: cytoscape.Core | null = null;
|
||||
let graphInitialized = $state(false);
|
||||
let selectedNode = $state<any>(null);
|
||||
let selectedEdge = $state<any>(null);
|
||||
|
||||
// Theme state
|
||||
let graphTheme = $state<"light" | "dark">("light");
|
||||
|
||||
// Layout state
|
||||
type LayoutType = "breadthfirst" | "grid" | "circle" | "concentric" | "cose";
|
||||
let currentLayout = $state<LayoutType>("breadthfirst");
|
||||
let showLayoutMenu = $state(false);
|
||||
|
||||
const layoutOptions: { value: LayoutType; label: string; icon: string }[] = [
|
||||
{ value: "breadthfirst", label: "Tree", icon: "tree" },
|
||||
{ value: "grid", label: "Grid", icon: "grid" },
|
||||
{ value: "circle", label: "Circle", icon: "circle" },
|
||||
{ value: "concentric", label: "Radial", icon: "radial" },
|
||||
{ value: "cose", label: "Force", icon: "force" },
|
||||
];
|
||||
|
||||
function buildGraphElements(nets: NetworkInfo[]) {
|
||||
interface ContainerResult {
|
||||
containerId: string;
|
||||
containerName: string;
|
||||
networks: {
|
||||
ipv4: string;
|
||||
netName: string;
|
||||
}[];
|
||||
}
|
||||
const elements: cytoscape.ElementDefinition[] = [];
|
||||
const networks = nets;
|
||||
|
||||
// Derive services from networks
|
||||
const serviceMap = networks.reduce<Record<string, ContainerResult>>((svcs, network) => {
|
||||
Object.entries(network.containers).forEach(([id, config]) => {
|
||||
if (!svcs[id]) {
|
||||
svcs[id] = {
|
||||
containerId: id,
|
||||
containerName: config.name,
|
||||
networks: [],
|
||||
};
|
||||
}
|
||||
|
||||
svcs[id].networks.push({
|
||||
ipv4: config.ipv4Address,
|
||||
netName: network.name,
|
||||
});
|
||||
});
|
||||
|
||||
return svcs;
|
||||
}, {});
|
||||
const services = Object.values(serviceMap);
|
||||
|
||||
// Add service nodes
|
||||
services.forEach((service) => {
|
||||
elements.push({
|
||||
data: {
|
||||
id: `service-${service.containerName}`,
|
||||
label: service.containerName,
|
||||
caption: '',
|
||||
type: "service",
|
||||
config: service,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// Add network nodes
|
||||
networks.forEach((network) => {
|
||||
const driver = network.driver;
|
||||
elements.push({
|
||||
data: {
|
||||
id: `network-${network.name}`,
|
||||
label: network.name,
|
||||
caption: driver,
|
||||
type: "network",
|
||||
driver: driver,
|
||||
external: !network.internal,
|
||||
config: network,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// Connect services to networks
|
||||
services.forEach((service) => {
|
||||
const serviceNetworks = service.networks;
|
||||
if (serviceNetworks) {
|
||||
serviceNetworks.forEach((network) => {
|
||||
const netName = network.netName;
|
||||
const foundName = networks.find((network) => network.name === netName);
|
||||
if (foundName || netName === "default") {
|
||||
const targetId = foundName ? `network-${netName}` : "network-default";
|
||||
const defaultNet = networks.find((network) => network.name === "default");
|
||||
if (netName === "default" && !defaultNet) {
|
||||
const defaultExists = elements.find((e) => e.data.id === "network-default");
|
||||
if (!defaultExists) {
|
||||
elements.push({
|
||||
data: {
|
||||
id: "network-default",
|
||||
label: "default",
|
||||
type: "network",
|
||||
driver: "bridge",
|
||||
external: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
elements.push({
|
||||
data: {
|
||||
id: `net-${service.containerName}-${netName}`,
|
||||
source: `service-${service.containerName}`,
|
||||
target: targetId,
|
||||
type: "network-connection",
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return elements;
|
||||
}
|
||||
|
||||
// SVG icons as data URLs for nodes
|
||||
function getSvgIcon(type: string, color: string): string {
|
||||
const icons: Record<string, string> = {
|
||||
service: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>`,
|
||||
network: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="16" y="16" width="6" height="6" rx="1"/><rect x="2" y="16" width="6" height="6" rx="1"/><rect x="9" y="2" width="6" height="6" rx="1"/><path d="M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3"/><path d="M12 12V8"/></svg>`,
|
||||
};
|
||||
const svg = icons[type] || icons.service;
|
||||
return `data:image/svg+xml,${encodeURIComponent(svg)}`;
|
||||
}
|
||||
|
||||
function createGraph(useExistingData = false, skipLayout = false) {
|
||||
if (!containerEl) return;
|
||||
|
||||
// Even if parsing failed, we get at least an empty structure to render
|
||||
if (!networks) {
|
||||
networks = [];
|
||||
}
|
||||
|
||||
const elements = buildGraphElements(networks);
|
||||
|
||||
// If skipping layout, store current positions before destroying
|
||||
let savedPositions: Map<string, { x: number; y: number }> | null = null;
|
||||
if (skipLayout && cy) {
|
||||
savedPositions = new Map();
|
||||
cy.nodes().forEach((node) => {
|
||||
const pos = node.position();
|
||||
savedPositions!.set(node.id(), { x: pos.x, y: pos.y });
|
||||
});
|
||||
}
|
||||
|
||||
if (cy) {
|
||||
cy.destroy();
|
||||
}
|
||||
|
||||
// Theme-based colors
|
||||
const isDark = graphTheme === "dark";
|
||||
const colors = {
|
||||
service: {
|
||||
bg: isDark ? "#3b82f6" : "#dbeafe",
|
||||
border: isDark ? "#2563eb" : "#93c5fd",
|
||||
text: isDark ? "#ffffff" : "#1e3a5f",
|
||||
icon: isDark ? "#ffffff" : "#2563eb",
|
||||
},
|
||||
network: {
|
||||
bg: isDark ? "#8b5cf6" : "#ede9fe",
|
||||
border: isDark ? "#7c3aed" : "#c4b5fd",
|
||||
text: isDark ? "#ffffff" : "#3b1e5f",
|
||||
icon: isDark ? "#ffffff" : "#7c3aed",
|
||||
},
|
||||
edge: isDark ? "#64748b" : "#94a3b8",
|
||||
selected: isDark ? "#fbbf24" : "#18181b",
|
||||
caption: isDark ? "rgba(255,255,255,0.7)" : "rgba(0,0,0,0.5)",
|
||||
};
|
||||
|
||||
cy = cytoscape({
|
||||
container: containerEl,
|
||||
elements,
|
||||
style: [
|
||||
// Service nodes
|
||||
{
|
||||
selector: 'node[type="service"]',
|
||||
style: {
|
||||
"background-color": colors.service.bg,
|
||||
"border-color": colors.service.border,
|
||||
"border-width": 2,
|
||||
label: (ele: any) => `${ele.data("label")}\n${ele.data("caption") || ""}`,
|
||||
color: colors.service.text,
|
||||
"text-valign": "center",
|
||||
"text-halign": "center",
|
||||
"font-size": "10px",
|
||||
"font-weight": 600,
|
||||
width: 150,
|
||||
height: 55,
|
||||
shape: "roundrectangle",
|
||||
"text-wrap": "wrap",
|
||||
"text-max-width": "115px",
|
||||
"text-overflow-wrap": "anywhere",
|
||||
"line-height": 1.2,
|
||||
"background-image": getSvgIcon("service", colors.service.icon),
|
||||
"background-width": "16px",
|
||||
"background-height": "16px",
|
||||
"background-position-x": "8px",
|
||||
"background-position-y": "50%",
|
||||
"background-clip": "none",
|
||||
"text-margin-x": 10,
|
||||
},
|
||||
},
|
||||
// Network nodes
|
||||
{
|
||||
selector: 'node[type="network"]',
|
||||
style: {
|
||||
"background-color": colors.network.bg,
|
||||
"border-color": colors.network.border,
|
||||
"border-width": 2,
|
||||
label: (ele: any) => `${ele.data("label")}\nnetwork: ${ele.data("caption") || "bridge"}`,
|
||||
color: colors.network.text,
|
||||
"text-valign": "center",
|
||||
"text-halign": "center",
|
||||
"font-size": "9px",
|
||||
"font-weight": 600,
|
||||
width: 120,
|
||||
height: 46,
|
||||
shape: "roundrectangle",
|
||||
"text-wrap": "wrap",
|
||||
"text-max-width": "90px",
|
||||
"text-overflow-wrap": "anywhere",
|
||||
"line-height": 1.2,
|
||||
"background-image": getSvgIcon("network", colors.network.icon),
|
||||
"background-width": "14px",
|
||||
"background-height": "14px",
|
||||
"background-position-x": "6px",
|
||||
"background-position-y": "50%",
|
||||
"background-clip": "none",
|
||||
"text-margin-x": 8,
|
||||
},
|
||||
},
|
||||
// Link edges
|
||||
{
|
||||
selector: 'edge[type="link"]',
|
||||
style: {
|
||||
width: 2,
|
||||
"line-color": "#64748b",
|
||||
"target-arrow-color": "#64748b",
|
||||
"target-arrow-shape": "triangle",
|
||||
"curve-style": "bezier",
|
||||
"line-style": "dashed",
|
||||
},
|
||||
},
|
||||
// Network connection edges
|
||||
{
|
||||
selector: 'edge[type="network-connection"]',
|
||||
style: {
|
||||
width: 1.5,
|
||||
"line-color": "#a78bfa",
|
||||
"curve-style": "bezier",
|
||||
"line-style": "dotted",
|
||||
},
|
||||
},
|
||||
// Selected node
|
||||
{
|
||||
selector: "node:selected",
|
||||
style: {
|
||||
"border-width": 3,
|
||||
"border-color": "#18181b",
|
||||
"overlay-color": "#18181b",
|
||||
"overlay-padding": 3,
|
||||
"overlay-opacity": 0.15,
|
||||
},
|
||||
},
|
||||
// Selected edge
|
||||
{
|
||||
selector: "edge:selected",
|
||||
style: {
|
||||
width: 3,
|
||||
"line-color": "#f59e0b",
|
||||
"target-arrow-color": "#f59e0b",
|
||||
},
|
||||
},
|
||||
// Connection mode - highlight services
|
||||
{
|
||||
selector: "node.connection-source",
|
||||
style: {
|
||||
"border-width": 4,
|
||||
"border-color": "#22c55e",
|
||||
"overlay-color": "#22c55e",
|
||||
"overlay-padding": 5,
|
||||
"overlay-opacity": 0.3,
|
||||
},
|
||||
},
|
||||
{
|
||||
selector: "node.connection-target",
|
||||
style: {
|
||||
"border-color": "#3b82f6",
|
||||
"border-width": 3,
|
||||
"overlay-color": "#3b82f6",
|
||||
"overlay-padding": 3,
|
||||
"overlay-opacity": 0.2,
|
||||
},
|
||||
},
|
||||
],
|
||||
layout:
|
||||
skipLayout && savedPositions
|
||||
? { name: "preset" }
|
||||
: {
|
||||
name: "breadthfirst",
|
||||
directed: true,
|
||||
padding: 50,
|
||||
spacingFactor: 1.5,
|
||||
avoidOverlap: true,
|
||||
nodeDimensionsIncludeLabels: true,
|
||||
},
|
||||
wheelSensitivity: 0.3,
|
||||
minZoom: 0.3,
|
||||
maxZoom: 3,
|
||||
});
|
||||
|
||||
// Restore saved positions if skipping layout
|
||||
if (skipLayout && savedPositions) {
|
||||
cy.nodes().forEach((node) => {
|
||||
const savedPos = savedPositions!.get(node.id());
|
||||
if (savedPos) {
|
||||
node.position(savedPos);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Handle node selection
|
||||
cy.on("tap", "node", (evt) => {
|
||||
const nodeData = evt.target.data();
|
||||
console.log("Node tapped:", nodeData);
|
||||
|
||||
selectedNode = nodeData;
|
||||
selectedEdge = null;
|
||||
console.log("selectedNode set to:", selectedNode);
|
||||
});
|
||||
|
||||
// Handle edge selection
|
||||
cy.on("tap", "edge", (evt) => {
|
||||
selectedEdge = evt.target.data();
|
||||
selectedNode = null;
|
||||
});
|
||||
|
||||
cy.on("tap", (evt) => {
|
||||
if (evt.target === cy) {
|
||||
selectedNode = null;
|
||||
selectedEdge = null;
|
||||
}
|
||||
});
|
||||
|
||||
graphInitialized = true;
|
||||
|
||||
// Ensure the graph renders correctly after container is sized
|
||||
setTimeout(() => {
|
||||
if (cy) {
|
||||
cy.resize();
|
||||
cy.fit(undefined, 50);
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
|
||||
function zoomIn() {
|
||||
if (cy) cy.zoom(cy.zoom() * 1.2);
|
||||
}
|
||||
|
||||
function zoomOut() {
|
||||
if (cy) cy.zoom(cy.zoom() / 1.2);
|
||||
}
|
||||
|
||||
function fitToScreen() {
|
||||
if (cy) cy.fit(undefined, 50);
|
||||
}
|
||||
|
||||
// Exported function to handle container resize
|
||||
export function resize() {
|
||||
if (cy && containerEl) {
|
||||
// Cytoscape caches container dimensions aggressively
|
||||
// We need to unmount and remount to the container
|
||||
cy!.unmount();
|
||||
|
||||
// Wait for DOM to update
|
||||
requestAnimationFrame(() => {
|
||||
if (cy && containerEl) {
|
||||
cy!.mount(containerEl);
|
||||
cy!.resize();
|
||||
cy!.fit(undefined, 50);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function getLayoutConfig(layoutName: LayoutType): cytoscape.LayoutOptions {
|
||||
const baseConfig = {
|
||||
padding: 50,
|
||||
avoidOverlap: true,
|
||||
nodeDimensionsIncludeLabels: true,
|
||||
};
|
||||
|
||||
switch (layoutName) {
|
||||
case "breadthfirst":
|
||||
return {
|
||||
...baseConfig,
|
||||
name: "breadthfirst",
|
||||
directed: true,
|
||||
spacingFactor: 1.5,
|
||||
};
|
||||
case "grid":
|
||||
return {
|
||||
...baseConfig,
|
||||
name: "grid",
|
||||
rows: undefined,
|
||||
cols: undefined,
|
||||
};
|
||||
case "circle":
|
||||
return {
|
||||
...baseConfig,
|
||||
name: "circle",
|
||||
spacingFactor: 1.2,
|
||||
};
|
||||
case "concentric":
|
||||
return {
|
||||
...baseConfig,
|
||||
name: "concentric",
|
||||
minNodeSpacing: 50,
|
||||
concentric: (node: any) => {
|
||||
// Services at center, resources around
|
||||
return node.data("type") === "service" ? 2 : 1;
|
||||
},
|
||||
levelWidth: () => 1,
|
||||
};
|
||||
case "cose":
|
||||
return {
|
||||
...baseConfig,
|
||||
name: "cose",
|
||||
idealEdgeLength: () => 100,
|
||||
nodeOverlap: 20,
|
||||
animate: true,
|
||||
animationDuration: 500,
|
||||
};
|
||||
default:
|
||||
return { ...baseConfig, name: layoutName };
|
||||
}
|
||||
}
|
||||
|
||||
function applyLayout(layoutName: LayoutType) {
|
||||
if (!cy) return;
|
||||
currentLayout = layoutName;
|
||||
showLayoutMenu = false;
|
||||
cy.layout(getLayoutConfig(layoutName)).run();
|
||||
cy.fit(undefined, 50);
|
||||
}
|
||||
|
||||
function resetLayout() {
|
||||
if (cy) {
|
||||
cy.layout(getLayoutConfig(currentLayout)).run();
|
||||
cy.fit(undefined, 50);
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
// Follow app theme from localStorage
|
||||
const appTheme = localStorage.getItem("theme");
|
||||
if (appTheme === "dark" || appTheme === "light") {
|
||||
graphTheme = appTheme;
|
||||
} else {
|
||||
// Fallback to system preference
|
||||
graphTheme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
|
||||
}
|
||||
});
|
||||
|
||||
// Create graph when container element becomes available
|
||||
$effect(() => {
|
||||
if (containerEl && networks && !graphInitialized) {
|
||||
createGraph();
|
||||
}
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (cy) {
|
||||
cy.destroy();
|
||||
cy = null;
|
||||
}
|
||||
});
|
||||
|
||||
function toggleGraphTheme() {
|
||||
graphTheme = graphTheme === "light" ? "dark" : "light";
|
||||
createGraph(true); // Recreate graph with new theme, preserve local edits
|
||||
}
|
||||
|
||||
function getNodeIcon(type: string) {
|
||||
switch (type) {
|
||||
case "service":
|
||||
return Box;
|
||||
case "network":
|
||||
return Network;
|
||||
default:
|
||||
return Database;
|
||||
}
|
||||
}
|
||||
|
||||
function getNodeColor(type: string) {
|
||||
switch (type) {
|
||||
case "service":
|
||||
return "bg-blue-500";
|
||||
case "network":
|
||||
return "bg-violet-500";
|
||||
default:
|
||||
return "bg-slate-500";
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full {className}">
|
||||
<!-- Toolbar -->
|
||||
<div class="flex items-center justify-between px-2 py-1.5 border-b border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-800 min-h-[40px]">
|
||||
<div class="flex items-center gap-2 flex-wrap"></div>
|
||||
<!-- Controls -->
|
||||
<div class="flex items-center gap-0.5">
|
||||
<!-- Layout selector -->
|
||||
<div class="relative">
|
||||
<button
|
||||
onclick={() => (showLayoutMenu = !showLayoutMenu)}
|
||||
class="h-6 px-2 flex items-center gap-1 rounded text-xs text-zinc-600 dark:text-zinc-300 hover:bg-zinc-200 dark:hover:bg-zinc-700 transition-colors"
|
||||
title="Change layout"
|
||||
>
|
||||
{#if currentLayout === "breadthfirst"}
|
||||
<GitBranch class="w-3 h-3" />
|
||||
{:else if currentLayout === "grid"}
|
||||
<LayoutGrid class="w-3 h-3" />
|
||||
{:else if currentLayout === "circle"}
|
||||
<Circle class="w-3 h-3" />
|
||||
{:else if currentLayout === "concentric"}
|
||||
<Target class="w-3 h-3" />
|
||||
{:else}
|
||||
<Sparkles class="w-3 h-3" />
|
||||
{/if}
|
||||
<ChevronDown class="w-3 h-3" />
|
||||
</button>
|
||||
{#if showLayoutMenu}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="absolute right-0 top-full mt-1 bg-white dark:bg-zinc-800 rounded-lg shadow-lg border border-zinc-200 dark:border-zinc-700 py-1 z-20 min-w-[120px]"
|
||||
onmouseleave={() => (showLayoutMenu = false)}
|
||||
>
|
||||
<button
|
||||
class="w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 hover:bg-zinc-100 dark:hover:bg-zinc-700 {currentLayout === 'breadthfirst'
|
||||
? 'text-blue-600 dark:text-blue-400 font-medium'
|
||||
: 'text-zinc-700 dark:text-zinc-200'}"
|
||||
onclick={() => applyLayout("breadthfirst")}
|
||||
>
|
||||
<GitBranch class="w-3.5 h-3.5" />
|
||||
Tree
|
||||
</button>
|
||||
<button
|
||||
class="w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 hover:bg-zinc-100 dark:hover:bg-zinc-700 {currentLayout === 'grid'
|
||||
? 'text-blue-600 dark:text-blue-400 font-medium'
|
||||
: 'text-zinc-700 dark:text-zinc-200'}"
|
||||
onclick={() => applyLayout("grid")}
|
||||
>
|
||||
<LayoutGrid class="w-3.5 h-3.5" />
|
||||
Grid
|
||||
</button>
|
||||
<button
|
||||
class="w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 hover:bg-zinc-100 dark:hover:bg-zinc-700 {currentLayout === 'circle'
|
||||
? 'text-blue-600 dark:text-blue-400 font-medium'
|
||||
: 'text-zinc-700 dark:text-zinc-200'}"
|
||||
onclick={() => applyLayout("circle")}
|
||||
>
|
||||
<Circle class="w-3.5 h-3.5" />
|
||||
Circle
|
||||
</button>
|
||||
<button
|
||||
class="w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 hover:bg-zinc-100 dark:hover:bg-zinc-700 {currentLayout === 'concentric'
|
||||
? 'text-blue-600 dark:text-blue-400 font-medium'
|
||||
: 'text-zinc-700 dark:text-zinc-200'}"
|
||||
onclick={() => applyLayout("concentric")}
|
||||
>
|
||||
<Target class="w-3.5 h-3.5" />
|
||||
Radial
|
||||
</button>
|
||||
<button
|
||||
class="w-full px-3 py-1.5 text-left text-xs flex items-center gap-2 hover:bg-zinc-100 dark:hover:bg-zinc-700 {currentLayout === 'cose'
|
||||
? 'text-blue-600 dark:text-blue-400 font-medium'
|
||||
: 'text-zinc-700 dark:text-zinc-200'}"
|
||||
onclick={() => applyLayout("cose")}
|
||||
>
|
||||
<Sparkles class="w-3.5 h-3.5" />
|
||||
Force
|
||||
</button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="w-px h-4 bg-zinc-300 dark:bg-zinc-600 mx-1"></div>
|
||||
<!-- Theme toggle -->
|
||||
<button
|
||||
onclick={toggleGraphTheme}
|
||||
class="h-6 w-6 flex items-center justify-center rounded text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200 hover:bg-zinc-200 dark:hover:bg-zinc-700 transition-colors"
|
||||
title={graphTheme === "light" ? "Switch to dark theme" : "Switch to light theme"}
|
||||
>
|
||||
{#if graphTheme === "light"}
|
||||
<Moon class="w-3.5 h-3.5" />
|
||||
{:else}
|
||||
<Sun class="w-3.5 h-3.5" />
|
||||
{/if}
|
||||
</button>
|
||||
<div class="w-px h-4 bg-zinc-300 dark:bg-zinc-600 mx-1"></div>
|
||||
<Button variant="ghost" size="sm" onclick={zoomOut} class="h-6 w-6 p-0 text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200">
|
||||
<ZoomOut class="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onclick={zoomIn} class="h-6 w-6 p-0 text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200">
|
||||
<ZoomIn class="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onclick={fitToScreen} class="h-6 w-6 p-0 text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200">
|
||||
<Maximize2 class="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onclick={resetLayout} class="h-6 w-6 p-0 text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200">
|
||||
<RotateCcw class="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 flex min-h-0 h-full">
|
||||
<!-- Graph container -->
|
||||
<div class="flex-1 relative h-full min-w-0 {graphTheme === 'dark' ? 'bg-zinc-900' : 'bg-zinc-100'}">
|
||||
<div bind:this={containerEl} class="w-full h-full"></div>
|
||||
|
||||
<!-- Footer: Legend -->
|
||||
<div class="absolute bottom-2 left-2 pointer-events-none z-10">
|
||||
<div
|
||||
class="flex items-center gap-2 text-xs bg-white/80 dark:bg-zinc-800/80 backdrop-blur-sm rounded px-2 py-1 shadow-sm border border-zinc-200/50 dark:border-zinc-700/50 whitespace-nowrap"
|
||||
>
|
||||
<div class="flex items-center gap-1 flex-shrink-0">
|
||||
<div class="w-2 h-2 rounded-sm bg-blue-500 flex-shrink-0"></div>
|
||||
<span class="text-zinc-600 dark:text-zinc-300">Service</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-1 flex-shrink-0">
|
||||
<div class="w-2 h-2 rounded-sm bg-violet-500 flex-shrink-0"></div>
|
||||
<span class="text-zinc-600 dark:text-zinc-300">Network</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Details panel (overlay) -->
|
||||
{#if selectedNode || selectedEdge}
|
||||
<div class="absolute top-0 right-0 bottom-0 w-[420px] border-l border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-800/95 shadow-lg z-20 flex flex-col">
|
||||
<!-- Sticky header -->
|
||||
{#if selectedNode}
|
||||
{@const NodeIcon = getNodeIcon(selectedNode.type)}
|
||||
<div class="sticky top-0 z-10 p-3 border-b border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-800/95">
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="p-1.5 rounded {getNodeColor(selectedNode.type)}">
|
||||
<NodeIcon class="w-3.5 h-3.5 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="font-semibold text-sm text-zinc-800 dark:text-zinc-100">
|
||||
{selectedNode.label}
|
||||
</h3>
|
||||
<p class="text-xs text-zinc-500 dark:text-zinc-400 capitalize">
|
||||
{selectedNode.type}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-6 w-6 p-0 text-zinc-500 hover:text-zinc-600 hover:bg-zinc-100 dark:hover:bg-zinc-700"
|
||||
onclick={() => {
|
||||
selectedNode = null;
|
||||
selectedEdge = null;
|
||||
}}
|
||||
title="Close"
|
||||
>
|
||||
<X class="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else if selectedEdge}
|
||||
<!-- Sticky header for edge -->
|
||||
<div class="sticky top-0 z-10 p-3 border-b border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-800/95">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 class="font-semibold text-sm text-zinc-800 dark:text-zinc-100 capitalize">
|
||||
{selectedEdge.type.replace("-", " ")}
|
||||
</h3>
|
||||
<p class="text-xs text-zinc-500 dark:text-zinc-400">
|
||||
{selectedEdge.source.replace(/^(service|network)-/, "")}
|
||||
→
|
||||
{selectedEdge.target.replace(/^(service|network)-/, "")}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-6 w-6 p-0 text-zinc-500 hover:text-zinc-600 hover:bg-zinc-100 dark:hover:bg-zinc-700"
|
||||
onclick={() => {
|
||||
selectedNode = null;
|
||||
selectedEdge = null;
|
||||
}}
|
||||
title="Close"
|
||||
>
|
||||
<X class="w-3.5 h-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<!-- Scrollable content -->
|
||||
<div class="flex-1 overflow-y-auto p-3">
|
||||
{#if selectedNode}
|
||||
{#if selectedNode.type === "service"}
|
||||
<div class="space-y-3 text-sm">
|
||||
<!-- Container Id -->
|
||||
<div class="space-y-1.5">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-xs font-medium text-zinc-600 dark:text-zinc-300">Container Id</span>
|
||||
</div>
|
||||
<Input value={selectedNode.config.containerId} placeholder="containerId" class="h-8 text-xs" readonly />
|
||||
</div>
|
||||
</div>
|
||||
{:else if selectedNode.type === "network"}
|
||||
<div class="space-y-3 text-sm">
|
||||
<!-- Driver -->
|
||||
<div class="space-y-1.5">
|
||||
<span class="text-xs font-medium text-zinc-600 dark:text-zinc-300">Driver</span>
|
||||
<!-- Simulate the select element -->
|
||||
<div class="flex items-center justify-between w-fit h-8 px-3 py-2 text-xs border rounded-md border-input bg-background shadow-sm dark:bg-input/30">
|
||||
<span class="flex items-center gap-1.5">
|
||||
{#if selectedNode.config.driver === "bridge"}
|
||||
<Share2 class="w-3.5 h-3.5 text-emerald-500" />
|
||||
{:else if selectedNode.config.driver === "host"}
|
||||
<Server class="w-3.5 h-3.5 text-sky-500" />
|
||||
{:else if selectedNode.config.driver === "overlay"}
|
||||
<Globe class="w-3.5 h-3.5 text-violet-500" />
|
||||
{:else if selectedNode.config.driver === "macvlan"}
|
||||
<MonitorSmartphone class="w-3.5 h-3.5 text-amber-500" />
|
||||
{:else if selectedNode.config.driver === "ipvlan"}
|
||||
<Cpu class="w-3.5 h-3.5 text-orange-500" />
|
||||
{:else}
|
||||
<CircleOff class="w-3.5 h-3.5 text-muted-foreground" />
|
||||
{/if}
|
||||
<span class="capitalize">{selectedNode.config.driver}</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- IPAM Config -->
|
||||
<div class="space-y-1.5">
|
||||
<span class="text-xs font-medium text-zinc-600 dark:text-zinc-300">IPAM configuration</span>
|
||||
<div class="space-y-4 pt-2">
|
||||
<div class="relative">
|
||||
<span class="absolute -top-2 left-2 text-[9px] text-zinc-400 bg-white dark:bg-zinc-800 px-1 z-10">Subnet</span>
|
||||
<Input value={selectedNode.config.ipam?.config?.[0].subnet} placeholder="172.20.0.0/16" class="h-9 pt-3 text-xs" readonly />
|
||||
</div>
|
||||
<div class="relative">
|
||||
<span class="absolute -top-2 left-2 text-[9px] text-zinc-400 bg-white dark:bg-zinc-800 px-1 z-10">Gateway</span>
|
||||
<Input value={selectedNode.config.ipam?.config?.[0].gateway} placeholder="172.20.0.1" class="h-9 pt-3 text-xs" readonly />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Boolean flags -->
|
||||
<div class="space-y-2 pointer-events-none select-none">
|
||||
<label class="flex items-center gap-2 cursor-pointer">
|
||||
<input type="checkbox" bind:checked={selectedNode.config.external} class="rounded border-zinc-300" />
|
||||
<span class="text-xs text-zinc-600">External network</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-2 cursor-pointer">
|
||||
<input type="checkbox" bind:checked={selectedNode.config.internal} class="rounded border-zinc-300" />
|
||||
<span class="text-xs text-zinc-600">Internal network</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-2 cursor-pointer">
|
||||
<input type="checkbox" bind:checked={selectedNode.config.attachable} class="rounded border-zinc-300" />
|
||||
<span class="text-xs text-zinc-600">Attachable</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{:else if selectedEdge}
|
||||
{#if selectedEdge.type === "network-connection"}
|
||||
<p class="text-xs text-zinc-500 dark:text-zinc-400">Service connected to this network.</p>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -11,7 +11,6 @@
|
||||
Shield,
|
||||
ShieldCheck,
|
||||
Key,
|
||||
KeyRound,
|
||||
RefreshCw,
|
||||
Check,
|
||||
Smartphone,
|
||||
@@ -23,8 +22,7 @@
|
||||
Camera,
|
||||
Trash2,
|
||||
TriangleAlert,
|
||||
Palette,
|
||||
Plus
|
||||
Palette
|
||||
} from 'lucide-svelte';
|
||||
import { authStore } from '$lib/stores/auth';
|
||||
import { formatDateTime } from '$lib/stores/settings';
|
||||
@@ -34,9 +32,6 @@
|
||||
import ChangePasswordModal from './ChangePasswordModal.svelte';
|
||||
import MfaSetupModal from './MfaSetupModal.svelte';
|
||||
import DisableMfaModal from './DisableMfaModal.svelte';
|
||||
import ApiTokenModal from './ApiTokenModal.svelte';
|
||||
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
|
||||
import * as Table from '$lib/components/ui/table';
|
||||
import ThemeSelector from '$lib/components/ThemeSelector.svelte';
|
||||
import { themeStore } from '$lib/stores/theme';
|
||||
import PageHeader from '$lib/components/PageHeader.svelte';
|
||||
@@ -78,49 +73,6 @@
|
||||
let mfaError = $state('');
|
||||
let showDisableMfaModal = $state(false);
|
||||
|
||||
// API tokens state
|
||||
interface ApiToken {
|
||||
id: number;
|
||||
name: string;
|
||||
tokenPrefix: string;
|
||||
lastUsed: string | null;
|
||||
expiresAt: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
let apiTokens = $state<ApiToken[]>([]);
|
||||
let showApiTokenModal = $state(false);
|
||||
let tokensLoading = $state(false);
|
||||
|
||||
async function fetchApiTokens() {
|
||||
tokensLoading = true;
|
||||
try {
|
||||
const response = await fetch('/api/auth/tokens');
|
||||
if (response.ok) {
|
||||
apiTokens = await response.json();
|
||||
}
|
||||
} catch {
|
||||
// Silently fail - tokens section will show empty
|
||||
} finally {
|
||||
tokensLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function revokeToken(tokenId: number) {
|
||||
try {
|
||||
const response = await fetch(`/api/auth/tokens/${tokenId}`, { method: 'DELETE' });
|
||||
if (response.ok) {
|
||||
apiTokens = apiTokens.filter(t => t.id !== tokenId);
|
||||
}
|
||||
} catch {
|
||||
// Ignore
|
||||
}
|
||||
}
|
||||
|
||||
function isTokenExpired(expiresAt: string | null): boolean {
|
||||
if (!expiresAt) return false;
|
||||
return new Date(expiresAt) < new Date();
|
||||
}
|
||||
|
||||
// Avatar state
|
||||
let showAvatarCropper = $state(false);
|
||||
let avatarSaving = $state(false);
|
||||
@@ -339,7 +291,6 @@
|
||||
if (!profileFetched) {
|
||||
profileFetched = true;
|
||||
fetchProfile();
|
||||
fetchApiTokens();
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -349,7 +300,7 @@
|
||||
<title>Profile - Dockhand</title>
|
||||
</svelte:head>
|
||||
|
||||
<div class="container mx-auto p-6">
|
||||
<div class="container mx-auto p-6 max-w-4xl">
|
||||
<div class="flex items-center gap-3 mb-6">
|
||||
<PageHeader icon={User} title="Profile" showConnection={false}>
|
||||
<p class="text-muted-foreground text-sm">Manage your account settings</p>
|
||||
@@ -379,9 +330,6 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Row 1: Account info + Profile details -->
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
|
||||
<!-- Account info card -->
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
@@ -483,14 +431,14 @@
|
||||
</Card.Root>
|
||||
|
||||
<!-- Profile details card -->
|
||||
<Card.Root class="flex flex-col">
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title class="flex items-center gap-2">
|
||||
<Mail class="w-5 h-5" />
|
||||
Profile details
|
||||
</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Content class="flex-1 flex flex-col space-y-4">
|
||||
<Card.Content class="space-y-4">
|
||||
{#if formError}
|
||||
<Alert.Root variant="destructive">
|
||||
<TriangleAlert class="h-4 w-4" />
|
||||
@@ -498,7 +446,7 @@
|
||||
</Alert.Root>
|
||||
{/if}
|
||||
|
||||
<div class="space-y-4 flex-1">
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<div class="space-y-2">
|
||||
<Label>Display name</Label>
|
||||
<Input
|
||||
@@ -529,13 +477,8 @@
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Row 2: Security + API tokens -->
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
|
||||
<!-- Security card -->
|
||||
<Card.Root class="flex flex-col">
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title class="flex items-center gap-2">
|
||||
<Shield class="w-5 h-5" />
|
||||
@@ -639,81 +582,6 @@
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
|
||||
<!-- API tokens card -->
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title class="flex items-center gap-2 justify-between">
|
||||
<span class="flex items-center gap-2">
|
||||
<KeyRound class="w-5 h-5" />
|
||||
API tokens
|
||||
</span>
|
||||
<Button variant="outline" size="sm" onclick={() => showApiTokenModal = true}>
|
||||
<Plus class="w-4 h-4 mr-1" />
|
||||
Generate token
|
||||
</Button>
|
||||
</Card.Title>
|
||||
<Card.Description>Create tokens for CI/CD pipelines and scripts</Card.Description>
|
||||
</Card.Header>
|
||||
<Card.Content>
|
||||
{#if tokensLoading}
|
||||
<p class="text-sm text-muted-foreground">Loading tokens...</p>
|
||||
{:else if apiTokens.length === 0}
|
||||
<p class="text-sm text-muted-foreground">No API tokens created yet.</p>
|
||||
{:else}
|
||||
<Table.Root>
|
||||
<Table.Header>
|
||||
<Table.Row>
|
||||
<Table.Head>Name</Table.Head>
|
||||
<Table.Head>Prefix</Table.Head>
|
||||
<Table.Head>Last used</Table.Head>
|
||||
<Table.Head>Expires</Table.Head>
|
||||
<Table.Head class="w-[80px]"></Table.Head>
|
||||
</Table.Row>
|
||||
</Table.Header>
|
||||
<Table.Body>
|
||||
{#each apiTokens as token (token.id)}
|
||||
<Table.Row class={isTokenExpired(token.expiresAt) ? 'opacity-50' : ''}>
|
||||
<Table.Cell class="font-medium">{token.name}</Table.Cell>
|
||||
<Table.Cell>
|
||||
<code class="text-xs bg-muted px-1.5 py-0.5 rounded">dh_{token.tokenPrefix}...</code>
|
||||
</Table.Cell>
|
||||
<Table.Cell class="text-sm text-muted-foreground">
|
||||
{token.lastUsed ? formatDateTime(token.lastUsed) : 'Never'}
|
||||
</Table.Cell>
|
||||
<Table.Cell class="text-sm">
|
||||
{#if isTokenExpired(token.expiresAt)}
|
||||
<Badge variant="destructive">Expired</Badge>
|
||||
{:else if token.expiresAt}
|
||||
{formatDateTime(token.expiresAt)}
|
||||
{:else}
|
||||
<span class="text-muted-foreground">Never</span>
|
||||
{/if}
|
||||
</Table.Cell>
|
||||
<Table.Cell>
|
||||
<ConfirmPopover
|
||||
title="Revoke token"
|
||||
description="This token will stop working immediately."
|
||||
confirmText="Revoke"
|
||||
onConfirm={() => revokeToken(token.id)}
|
||||
>
|
||||
<Button variant="ghost" size="sm" class="text-destructive hover:text-destructive">
|
||||
<Trash2 class="w-4 h-4" />
|
||||
</Button>
|
||||
</ConfirmPopover>
|
||||
</Table.Cell>
|
||||
</Table.Row>
|
||||
{/each}
|
||||
</Table.Body>
|
||||
</Table.Root>
|
||||
{/if}
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Row 3: Appearance (left-aligned with Security) -->
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
|
||||
<!-- Appearance card -->
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
@@ -727,8 +595,6 @@
|
||||
<ThemeSelector userId={profile.id} />
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -759,13 +625,6 @@
|
||||
/>
|
||||
{/if}
|
||||
|
||||
<!-- API Token Modal -->
|
||||
<ApiTokenModal
|
||||
bind:open={showApiTokenModal}
|
||||
onCreated={fetchApiTokens}
|
||||
provider={profile?.provider ?? 'local'}
|
||||
/>
|
||||
|
||||
<!-- Avatar Cropper Modal -->
|
||||
<AvatarCropper
|
||||
show={showAvatarCropper}
|
||||
|
||||
@@ -1,237 +0,0 @@
|
||||
<script lang="ts">
|
||||
import * as Dialog from '$lib/components/ui/dialog';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import { Label } from '$lib/components/ui/label';
|
||||
import * as Select from '$lib/components/ui/select';
|
||||
import * as Alert from '$lib/components/ui/alert';
|
||||
import { KeyRound, Copy, Check, TriangleAlert } from 'lucide-svelte';
|
||||
|
||||
let {
|
||||
open = $bindable(false),
|
||||
onCreated,
|
||||
provider = 'local'
|
||||
}: {
|
||||
open: boolean;
|
||||
onCreated: () => void;
|
||||
provider?: string;
|
||||
} = $props();
|
||||
|
||||
let name = $state('');
|
||||
let password = $state('');
|
||||
let expirationOption = $state('none');
|
||||
let customDate = $state('');
|
||||
let creating = $state(false);
|
||||
let error = $state('');
|
||||
|
||||
const isLocalUser = $derived(provider === 'local');
|
||||
|
||||
// After creation
|
||||
let createdToken = $state('');
|
||||
let copied = $state(false);
|
||||
|
||||
function reset() {
|
||||
name = '';
|
||||
password = '';
|
||||
expirationOption = 'none';
|
||||
customDate = '';
|
||||
creating = false;
|
||||
error = '';
|
||||
createdToken = '';
|
||||
copied = false;
|
||||
}
|
||||
|
||||
function getExpiresAt(): string | null {
|
||||
const now = new Date();
|
||||
switch (expirationOption) {
|
||||
case '30d':
|
||||
return new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString();
|
||||
case '90d':
|
||||
return new Date(now.getTime() + 90 * 24 * 60 * 60 * 1000).toISOString();
|
||||
case '1y':
|
||||
return new Date(now.getTime() + 365 * 24 * 60 * 60 * 1000).toISOString();
|
||||
case 'custom':
|
||||
return customDate ? new Date(customDate + 'T23:59:59').toISOString() : null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function createToken() {
|
||||
if (!name.trim()) {
|
||||
error = 'Token name is required';
|
||||
return;
|
||||
}
|
||||
if (isLocalUser && !password) {
|
||||
error = 'Password is required';
|
||||
return;
|
||||
}
|
||||
|
||||
creating = true;
|
||||
error = '';
|
||||
|
||||
try {
|
||||
const payload: Record<string, any> = {
|
||||
name: name.trim(),
|
||||
expiresAt: getExpiresAt()
|
||||
};
|
||||
if (isLocalUser) {
|
||||
payload.password = password;
|
||||
}
|
||||
|
||||
const response = await fetch('/api/auth/tokens', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
createdToken = data.token;
|
||||
} else {
|
||||
const data = await response.json();
|
||||
error = data.error || 'Failed to create token';
|
||||
}
|
||||
} catch {
|
||||
error = 'Failed to create token';
|
||||
} finally {
|
||||
creating = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function copyToken() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(createdToken);
|
||||
copied = true;
|
||||
setTimeout(() => copied = false, 2000);
|
||||
} catch {
|
||||
// Fallback: select the input text
|
||||
}
|
||||
}
|
||||
|
||||
function handleClose() {
|
||||
if (createdToken) {
|
||||
onCreated();
|
||||
}
|
||||
open = false;
|
||||
// Reset after animation
|
||||
setTimeout(reset, 200);
|
||||
}
|
||||
|
||||
// Get minimum date for custom picker (tomorrow)
|
||||
const minDate = $derived(() => {
|
||||
const tomorrow = new Date();
|
||||
tomorrow.setDate(tomorrow.getDate() + 1);
|
||||
return tomorrow.toISOString().split('T')[0];
|
||||
});
|
||||
</script>
|
||||
|
||||
<Dialog.Root bind:open onOpenChange={(v) => { if (!v) handleClose(); }}>
|
||||
<Dialog.Content class="max-w-md">
|
||||
<Dialog.Header>
|
||||
<Dialog.Title class="flex items-center gap-2">
|
||||
<KeyRound class="w-5 h-5" />
|
||||
{createdToken ? 'Token created' : 'Generate API token'}
|
||||
</Dialog.Title>
|
||||
</Dialog.Header>
|
||||
|
||||
{#if createdToken}
|
||||
<!-- Token created - show it once -->
|
||||
<div class="space-y-4">
|
||||
<Alert.Root variant="destructive">
|
||||
<TriangleAlert class="h-4 w-4" />
|
||||
<Alert.Description>
|
||||
Copy this token now. It will not be shown again.
|
||||
</Alert.Description>
|
||||
</Alert.Root>
|
||||
|
||||
<div class="flex gap-2">
|
||||
<Input
|
||||
value={createdToken}
|
||||
readonly
|
||||
class="font-mono text-xs"
|
||||
/>
|
||||
<Button variant="outline" size="icon" onclick={copyToken}>
|
||||
{#if copied}
|
||||
<Check class="w-4 h-4 text-green-500" />
|
||||
{:else}
|
||||
<Copy class="w-4 h-4" />
|
||||
{/if}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end">
|
||||
<Button onclick={handleClose}>Done</Button>
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Token creation form -->
|
||||
<div class="space-y-4">
|
||||
<div class="space-y-2">
|
||||
<Label for="token-name">Name</Label>
|
||||
<Input
|
||||
id="token-name"
|
||||
bind:value={name}
|
||||
placeholder="e.g., CI/CD pipeline"
|
||||
maxlength={255}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{#if isLocalUser}
|
||||
<div class="space-y-2">
|
||||
<Label for="token-password">Password</Label>
|
||||
<Input
|
||||
id="token-password"
|
||||
type="password"
|
||||
bind:value={password}
|
||||
placeholder="Confirm your password"
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="space-y-2">
|
||||
<Label>Expiration</Label>
|
||||
<Select.Root type="single" bind:value={expirationOption}>
|
||||
<Select.Trigger class="w-full">
|
||||
{#if expirationOption === 'none'}No expiration
|
||||
{:else if expirationOption === '30d'}30 days
|
||||
{:else if expirationOption === '90d'}90 days
|
||||
{:else if expirationOption === '1y'}1 year
|
||||
{:else if expirationOption === 'custom'}Custom date
|
||||
{/if}
|
||||
</Select.Trigger>
|
||||
<Select.Content>
|
||||
<Select.Item value="none">No expiration</Select.Item>
|
||||
<Select.Item value="30d">30 days</Select.Item>
|
||||
<Select.Item value="90d">90 days</Select.Item>
|
||||
<Select.Item value="1y">1 year</Select.Item>
|
||||
<Select.Item value="custom">Custom date</Select.Item>
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
|
||||
{#if expirationOption === 'custom'}
|
||||
<Input
|
||||
type="date"
|
||||
bind:value={customDate}
|
||||
min={minDate()}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if error}
|
||||
<Alert.Root variant="destructive">
|
||||
<TriangleAlert class="h-4 w-4" />
|
||||
<Alert.Description>{error}</Alert.Description>
|
||||
</Alert.Root>
|
||||
{/if}
|
||||
|
||||
<div class="flex justify-end gap-2">
|
||||
<Button variant="outline" onclick={handleClose}>Cancel</Button>
|
||||
<Button onclick={createToken} disabled={creating || !name.trim() || (isLocalUser && !password)}>
|
||||
{creating ? 'Creating...' : 'Generate token'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</Dialog.Content>
|
||||
</Dialog.Root>
|
||||
@@ -188,10 +188,8 @@
|
||||
<Label>Verification code</Label>
|
||||
<Input
|
||||
bind:value={token}
|
||||
name="totp"
|
||||
placeholder="Enter 6-digit code"
|
||||
maxlength={6}
|
||||
autocomplete="one-time-code"
|
||||
/>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
Enter the code from your authenticator app to verify setup
|
||||
|
||||
@@ -41,17 +41,13 @@
|
||||
import { DataGrid } from '$lib/components/data-grid';
|
||||
import type { DataGridRowState } from '$lib/components/data-grid';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { formatDateTime, getTimeFormat, appSettings } from '$lib/stores/settings';
|
||||
import { formatDateTime, appSettings } from '$lib/stores/settings';
|
||||
import EnvironmentIcon from '$lib/components/EnvironmentIcon.svelte';
|
||||
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
|
||||
import ScannerSeverityPills from '$lib/components/ScannerSeverityPills.svelte';
|
||||
import VulnerabilityCriteriaBadge from '$lib/components/VulnerabilityCriteriaBadge.svelte';
|
||||
import UpdateSummaryStats from '$lib/components/UpdateSummaryStats.svelte';
|
||||
import ExecutionLogViewer from '$lib/components/ExecutionLogViewer.svelte';
|
||||
import { canAccess } from '$lib/stores/auth';
|
||||
|
||||
const canEditSchedules = $derived($canAccess('schedules', 'edit'));
|
||||
const canRunSchedules = $derived($canAccess('schedules', 'run'));
|
||||
import { vulnerabilityCriteriaIcons, vulnerabilityCriteriaLabels } from '$lib/utils/update-steps';
|
||||
import type { VulnerabilityCriteria } from '$lib/server/db';
|
||||
import cronstrue from 'cronstrue';
|
||||
@@ -187,7 +183,7 @@
|
||||
|
||||
// State
|
||||
let schedules = $state<Schedule[]>([]);
|
||||
let environments = $state<{ id: number; name: string; icon: string; timezone?: string }[]>([]);
|
||||
let environments = $state<{ id: number; name: string; icon: string }[]>([]);
|
||||
let loading = $state(true);
|
||||
let refreshing = $state(false);
|
||||
let searchQuery = $state('');
|
||||
@@ -208,11 +204,6 @@
|
||||
let selectedExecution = $state<ScheduleExecution | null>(null);
|
||||
let loadingExecutionDetail = $state(false);
|
||||
let logDarkMode = $state(true);
|
||||
let selectedExecutionTimezone = $derived(
|
||||
selectedExecution?.environmentId
|
||||
? environments.find(e => e.id === selectedExecution!.environmentId)?.timezone
|
||||
: undefined
|
||||
);
|
||||
|
||||
function toggleLogTheme() {
|
||||
logDarkMode = !logDarkMode;
|
||||
@@ -745,21 +736,9 @@
|
||||
}
|
||||
}
|
||||
|
||||
function formatTimestamp(iso: string | null, tz?: string): string {
|
||||
function formatTimestamp(iso: string | null): string {
|
||||
if (!iso) return '-';
|
||||
if (!tz) return formatDateTime(iso, true);
|
||||
const d = new Date(iso);
|
||||
if (isNaN(d.getTime())) return iso;
|
||||
return new Intl.DateTimeFormat('en-GB', {
|
||||
timeZone: tz,
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: getTimeFormat() === '12h'
|
||||
}).format(d);
|
||||
return formatDateTime(iso, true);
|
||||
}
|
||||
|
||||
function formatDuration(ms: number | null): string {
|
||||
@@ -1308,31 +1287,27 @@
|
||||
<FileText class="w-3 h-3 text-muted-foreground hover:text-blue-500" />
|
||||
</button>
|
||||
{/if}
|
||||
{#if canEditSchedules}
|
||||
<button
|
||||
type="button"
|
||||
onclick={(e) => { e.stopPropagation(); toggleScheduleEnabled(schedule); }}
|
||||
title={schedule.enabled ? 'Pause schedule' : 'Resume schedule'}
|
||||
class="p-0.5 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer"
|
||||
>
|
||||
{#if schedule.enabled}
|
||||
<Pause class="w-3 h-3 text-muted-foreground hover:text-amber-500" />
|
||||
{:else}
|
||||
<PlayCircle class="w-3 h-3 text-muted-foreground hover:text-green-500" />
|
||||
{/if}
|
||||
</button>
|
||||
{/if}
|
||||
{#if canRunSchedules}
|
||||
<button
|
||||
type="button"
|
||||
onclick={(e) => { e.stopPropagation(); triggerSchedule(schedule); }}
|
||||
title="Run now"
|
||||
class="p-0.5 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer"
|
||||
>
|
||||
<Play class="w-3 h-3 text-muted-foreground hover:text-green-500" />
|
||||
</button>
|
||||
{/if}
|
||||
{#if canEditSchedules && !schedule.isSystem}
|
||||
<button
|
||||
type="button"
|
||||
onclick={(e) => { e.stopPropagation(); toggleScheduleEnabled(schedule); }}
|
||||
title={schedule.enabled ? 'Pause schedule' : 'Resume schedule'}
|
||||
class="p-0.5 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer"
|
||||
>
|
||||
{#if schedule.enabled}
|
||||
<Pause class="w-3 h-3 text-muted-foreground hover:text-amber-500" />
|
||||
{:else}
|
||||
<PlayCircle class="w-3 h-3 text-muted-foreground hover:text-green-500" />
|
||||
{/if}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onclick={(e) => { e.stopPropagation(); triggerSchedule(schedule); }}
|
||||
title="Run now"
|
||||
class="p-0.5 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer"
|
||||
>
|
||||
<Play class="w-3 h-3 text-muted-foreground hover:text-green-500" />
|
||||
</button>
|
||||
{#if !schedule.isSystem}
|
||||
{@const scheduleKey = getScheduleKey(schedule)}
|
||||
<ConfirmPopover
|
||||
open={confirmDeleteId === scheduleKey}
|
||||
@@ -1360,7 +1335,7 @@
|
||||
<div class="p-4 pl-12 shadow-inner bg-muted isolate sticky left-0 max-w-[calc(100vw-18rem)]">
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<h4 class="text-xs font-medium">Execution history</h4>
|
||||
{#if executions.length > 0 && canEditSchedules}
|
||||
{#if executions.length > 0}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => deleteAllExecutions(schedule)}
|
||||
@@ -1437,16 +1412,14 @@
|
||||
>
|
||||
<FileText class="w-3 h-3 text-muted-foreground hover:text-blue-500" />
|
||||
</button>
|
||||
{#if canEditSchedules}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => deleteExecution(schedule, exec.id)}
|
||||
title="Delete execution"
|
||||
class="p-0.5 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer"
|
||||
>
|
||||
<Trash2 class="w-3 h-3 text-muted-foreground hover:text-red-500" />
|
||||
</button>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => deleteExecution(schedule, exec.id)}
|
||||
title="Delete execution"
|
||||
class="p-0.5 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer"
|
||||
>
|
||||
<Trash2 class="w-3 h-3 text-muted-foreground hover:text-red-500" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -1518,7 +1491,7 @@
|
||||
</Dialog.Title>
|
||||
{#if selectedExecution}
|
||||
<span class="text-xs text-muted-foreground shrink-0 pr-6 whitespace-nowrap inline-flex items-center gap-1">
|
||||
{formatTimestamp(selectedExecution.triggeredAt, selectedExecutionTimezone)} · <Timer class="w-3 h-3 -mt-px" /> {formatDuration(selectedExecution.duration)}
|
||||
{formatTimestamp(selectedExecution.triggeredAt)} · <Timer class="w-3 h-3 -mt-px" /> {formatDuration(selectedExecution.duration)}
|
||||
</span>
|
||||
{/if}
|
||||
</Dialog.Header>
|
||||
@@ -1655,7 +1628,6 @@
|
||||
<ExecutionLogViewer
|
||||
logs={selectedExecution.logs}
|
||||
darkMode={logDarkMode}
|
||||
timezone={selectedExecutionTimezone}
|
||||
onToggleTheme={toggleLogTheme}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -135,9 +135,7 @@
|
||||
{ key: 'view', label: 'View audit logs' }
|
||||
],
|
||||
schedules: [
|
||||
{ key: 'view', label: 'View schedules' },
|
||||
{ key: 'edit', label: 'Edit schedules' },
|
||||
{ key: 'run', label: 'Run schedules' }
|
||||
{ key: 'view', label: 'View schedules' }
|
||||
]
|
||||
};
|
||||
|
||||
@@ -244,7 +242,6 @@
|
||||
disconnect: Unplug,
|
||||
edit: Pencil,
|
||||
test: Play,
|
||||
run: Play,
|
||||
manage: Settings
|
||||
};
|
||||
|
||||
|
||||
@@ -8,9 +8,8 @@
|
||||
import { TogglePill, ToggleSwitch } from '$lib/components/ui/toggle-pill';
|
||||
import CronEditor from '$lib/components/cron-editor.svelte';
|
||||
import TimezoneSelector from '$lib/components/TimezoneSelector.svelte';
|
||||
import { Eye, Bell, Database, Calendar, ShieldCheck, FileText, AlertTriangle, HelpCircle, Globe, Activity, Clock, Info, Save, RotateCcw, LayoutDashboard, Tags } from 'lucide-svelte';
|
||||
import CodeEditor from '$lib/components/CodeEditor.svelte';
|
||||
import { appSettings, type DateFormat, type DownloadFormat, type EventCollectionMode, type LabelFilterMode } from '$lib/stores/settings';
|
||||
import { Eye, Bell, Database, Calendar, ShieldCheck, FileText, AlertTriangle, HelpCircle, Globe, Activity, Clock, Info } from 'lucide-svelte';
|
||||
import { appSettings, type DateFormat, type DownloadFormat, type EventCollectionMode } from '$lib/stores/settings';
|
||||
import { canAccess, authStore } from '$lib/stores/auth';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import ThemeSelector from '$lib/components/ThemeSelector.svelte';
|
||||
@@ -28,46 +27,6 @@
|
||||
let defaultTrivyArgs = $derived($appSettings.defaultTrivyArgs);
|
||||
let defaultGrypeImage = $derived($appSettings.defaultGrypeImage);
|
||||
let defaultTrivyImage = $derived($appSettings.defaultTrivyImage);
|
||||
let defaultComposeTemplate = $derived($appSettings.defaultComposeTemplate);
|
||||
let labelFilterMode = $derived($appSettings.labelFilterMode);
|
||||
let composeTemplateWIP = $state('');
|
||||
let composeTemplateInitialized = false;
|
||||
|
||||
$effect(() => {
|
||||
if (!composeTemplateInitialized && defaultComposeTemplate !== undefined) {
|
||||
composeTemplateWIP = defaultComposeTemplate;
|
||||
composeTemplateInitialized = true;
|
||||
}
|
||||
});
|
||||
|
||||
const builtinComposeTemplate = `version: "3.8"
|
||||
|
||||
services:
|
||||
app:
|
||||
image: nginx:alpine
|
||||
ports:
|
||||
- "8080:80"
|
||||
environment:
|
||||
- APP_ENV=\${APP_ENV:-production}
|
||||
volumes:
|
||||
- ./html:/usr/share/nginx/html:ro
|
||||
restart: unless-stopped
|
||||
|
||||
# Add more services as needed
|
||||
# networks:
|
||||
# default:
|
||||
# driver: bridge
|
||||
`;
|
||||
|
||||
function saveComposeTemplate() {
|
||||
appSettings.setDefaultComposeTemplate(composeTemplateWIP);
|
||||
toast.success('Compose template updated');
|
||||
}
|
||||
|
||||
function revertComposeTemplate() {
|
||||
composeTemplateWIP = builtinComposeTemplate;
|
||||
toast.info('Template reverted to default');
|
||||
}
|
||||
let scheduleRetentionDays = $derived($appSettings.scheduleRetentionDays);
|
||||
let eventRetentionDays = $derived($appSettings.eventRetentionDays);
|
||||
let scheduleCleanupCron = $derived($appSettings.scheduleCleanupCron);
|
||||
@@ -135,15 +94,13 @@ services:
|
||||
}
|
||||
|
||||
function handleScheduleCleanupEnabledChange() {
|
||||
const newState = !scheduleCleanupEnabled;
|
||||
appSettings.setScheduleCleanupEnabled(newState);
|
||||
toast.success(newState ? 'Schedule cleanup enabled' : 'Schedule cleanup disabled');
|
||||
appSettings.setScheduleCleanupEnabled(!scheduleCleanupEnabled);
|
||||
toast.success(scheduleCleanupEnabled ? 'Schedule cleanup disabled' : 'Schedule cleanup enabled');
|
||||
}
|
||||
|
||||
function handleEventCleanupEnabledChange() {
|
||||
const newState = !eventCleanupEnabled;
|
||||
appSettings.setEventCleanupEnabled(newState);
|
||||
toast.success(newState ? 'Event cleanup enabled' : 'Event cleanup disabled');
|
||||
appSettings.setEventCleanupEnabled(!eventCleanupEnabled);
|
||||
toast.success(eventCleanupEnabled ? 'Event cleanup disabled' : 'Event cleanup enabled');
|
||||
}
|
||||
|
||||
function handleGrypeImageBlur(e: Event) {
|
||||
@@ -242,9 +199,9 @@ services:
|
||||
<Label>Show stopped containers</Label>
|
||||
<TogglePill
|
||||
checked={showStoppedContainers}
|
||||
onchange={(checked) => {
|
||||
appSettings.setShowStoppedContainers(checked);
|
||||
toast.success(checked ? 'Stopped containers shown' : 'Stopped containers hidden');
|
||||
onchange={() => {
|
||||
appSettings.setShowStoppedContainers(!showStoppedContainers);
|
||||
toast.success(showStoppedContainers ? 'Stopped containers hidden' : 'Stopped containers shown');
|
||||
}}
|
||||
disabled={!$canAccess('settings', 'edit')}
|
||||
/>
|
||||
@@ -256,9 +213,9 @@ services:
|
||||
<Label>Highlight available updates</Label>
|
||||
<TogglePill
|
||||
checked={highlightUpdates}
|
||||
onchange={(checked) => {
|
||||
appSettings.setHighlightUpdates(checked);
|
||||
toast.success(checked ? 'Update highlighting enabled' : 'Update highlighting disabled');
|
||||
onchange={() => {
|
||||
appSettings.setHighlightUpdates(!highlightUpdates);
|
||||
toast.success(highlightUpdates ? 'Update highlighting disabled' : 'Update highlighting enabled');
|
||||
}}
|
||||
disabled={!$canAccess('settings', 'edit')}
|
||||
/>
|
||||
@@ -270,9 +227,9 @@ services:
|
||||
<Label>Compact port display</Label>
|
||||
<TogglePill
|
||||
checked={compactPorts}
|
||||
onchange={(checked) => {
|
||||
appSettings.setCompactPorts(checked);
|
||||
toast.success(checked ? 'Compact port display enabled' : 'Showing all ports');
|
||||
onchange={() => {
|
||||
appSettings.setCompactPorts(!compactPorts);
|
||||
toast.success(compactPorts ? 'Showing all ports' : 'Compact port display enabled');
|
||||
}}
|
||||
disabled={!$canAccess('settings', 'edit')}
|
||||
/>
|
||||
@@ -380,9 +337,9 @@ services:
|
||||
<Label>Confirm destructive actions</Label>
|
||||
<TogglePill
|
||||
checked={confirmDestructive}
|
||||
onchange={(checked) => {
|
||||
appSettings.setConfirmDestructive(checked);
|
||||
toast.success(checked ? 'Confirmations enabled' : 'Confirmations disabled');
|
||||
onchange={() => {
|
||||
appSettings.setConfirmDestructive(!confirmDestructive);
|
||||
toast.success(confirmDestructive ? 'Confirmations disabled' : 'Confirmations enabled');
|
||||
}}
|
||||
disabled={!$canAccess('settings', 'edit')}
|
||||
/>
|
||||
@@ -448,9 +405,9 @@ services:
|
||||
<Label>Format log timestamps</Label>
|
||||
<TogglePill
|
||||
checked={formatLogTimestamps}
|
||||
onchange={(checked) => {
|
||||
appSettings.setFormatLogTimestamps(checked);
|
||||
toast.success(checked ? 'Log timestamp formatting enabled' : 'Log timestamp formatting disabled');
|
||||
onchange={() => {
|
||||
appSettings.setFormatLogTimestamps(!formatLogTimestamps);
|
||||
toast.success(formatLogTimestamps ? 'Log timestamp formatting disabled' : 'Log timestamp formatting enabled');
|
||||
}}
|
||||
disabled={!$canAccess('settings', 'edit')}
|
||||
/>
|
||||
@@ -466,39 +423,6 @@ services:
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title class="text-sm font-medium flex items-center gap-2">
|
||||
<FileText class="w-4 h-4" />
|
||||
Compose template
|
||||
</Card.Title>
|
||||
<p class="text-xs text-muted-foreground">Default YAML content when creating a new stack.</p>
|
||||
</Card.Header>
|
||||
<Card.Content class="space-y-3">
|
||||
<div class="h-64">
|
||||
<CodeEditor
|
||||
value={composeTemplateWIP}
|
||||
onchange={(v) => { composeTemplateWIP = v; }}
|
||||
language="yaml"
|
||||
readonly={!$canAccess('settings', 'edit')}
|
||||
class="h-full rounded-md overflow-hidden border border-zinc-200 dark:border-zinc-700"
|
||||
/>
|
||||
</div>
|
||||
{#if $canAccess('settings', 'edit')}
|
||||
<div class="flex gap-2">
|
||||
<Button size="sm" variant="outline" onclick={saveComposeTemplate}>
|
||||
<Save class="w-3.5 h-3.5" />
|
||||
Save template
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onclick={revertComposeTemplate}>
|
||||
<RotateCcw class="w-3.5 h-3.5" />
|
||||
Revert to default
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Right column -->
|
||||
@@ -760,43 +684,6 @@ services:
|
||||
</div>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
|
||||
<Card.Root>
|
||||
<Card.Header>
|
||||
<Card.Title class="text-sm font-medium flex items-center gap-2">
|
||||
<LayoutDashboard class="w-4 h-4" />
|
||||
Dashboard
|
||||
</Card.Title>
|
||||
</Card.Header>
|
||||
<Card.Content class="space-y-4">
|
||||
<div class="space-y-3">
|
||||
<div class="space-y-1">
|
||||
<div class="flex items-center gap-3">
|
||||
<Label>Label filter matching</Label>
|
||||
<Tooltip.Root>
|
||||
<Tooltip.Trigger>
|
||||
<HelpCircle class="w-3.5 h-3.5 text-muted-foreground" />
|
||||
</Tooltip.Trigger>
|
||||
<Tooltip.Content class="w-80">
|
||||
<p class="text-xs">
|
||||
Controls how multiple selected labels filter environments on the dashboard.
|
||||
<strong>"Any"</strong>: shows environments that have at least one of the selected labels.
|
||||
<strong>"All"</strong>: shows only environments that have every selected label.
|
||||
</p>
|
||||
</Tooltip.Content>
|
||||
</Tooltip.Root>
|
||||
<ToggleSwitch
|
||||
value={labelFilterMode}
|
||||
leftValue="any"
|
||||
rightValue="all"
|
||||
onchange={(mode) => appSettings.setLabelFilterMode(mode as LabelFilterMode)}
|
||||
disabled={!$canAccess('settings', 'edit')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card.Content>
|
||||
</Card.Root>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -420,15 +420,13 @@ discord://webhook_id/webhook_token
|
||||
slack://token_a/token_b/token_c
|
||||
mmost://hostname/webhook-token
|
||||
tgram://bot_token/chat_id
|
||||
tgram://bot_token/chat_id:topic_id
|
||||
ntfy://my-topic
|
||||
pushover://user_key/api_token
|
||||
workflows://hostname/workflow/signature
|
||||
jsons://hostname/webhook/path"
|
||||
class="flex min-h-[220px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||
></textarea>
|
||||
<p class="text-xs text-muted-foreground">
|
||||
Supports Gotify (gotify:// or gotifys:// for HTTPS), Discord, Slack, Mattermost (mmost:// or mmosts://), Telegram, ntfy, Pushover, Workflows (for e.g. Microsoft Teams), and generic JSON webhooks.
|
||||
Supports Gotify (gotify:// or gotifys:// for HTTPS), Discord, Slack, Mattermost (mmost:// or mmosts://), Telegram, ntfy, Pushover, and generic JSON webhooks.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -10,12 +10,10 @@
|
||||
import { Badge } from '$lib/components/ui/badge';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import { Input } from '$lib/components/ui/input';
|
||||
import { Checkbox } from '$lib/components/ui/checkbox';
|
||||
import * as Tooltip from '$lib/components/ui/tooltip';
|
||||
import * as Popover from '$lib/components/ui/popover';
|
||||
import MultiSelectFilter from '$lib/components/MultiSelectFilter.svelte';
|
||||
import { Play, Square, Trash2, Plus, ArrowBigDown, Search, Pencil, ExternalLink, GitBranch, RefreshCw, Loader2, FileCode, FileText, FileOutput, Box, RotateCcw, ScrollText, Terminal, Eye, Network, HardDrive, Heart, HeartPulse, HeartOff, ChevronsUpDown, ChevronsDownUp, Rocket, AlertTriangle, X, Layers, Pause, CircleDashed, Skull, FolderOpen, Variable, Clock, RotateCw, Import, Ship, Cable, LayoutPanelLeft, Rows3, GripVertical } from 'lucide-svelte';
|
||||
import { formatPorts } from '$lib/utils/port-format';
|
||||
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
|
||||
import BatchOperationModal from '$lib/components/BatchOperationModal.svelte';
|
||||
import type { ComposeStackInfo, ContainerStats } from '$lib/types';
|
||||
@@ -262,7 +260,7 @@
|
||||
if (stats) {
|
||||
cpuPercent += stats.cpuPercent;
|
||||
memoryUsage += stats.memoryUsage;
|
||||
memoryLimit = Math.max(memoryLimit, stats.memoryLimit);
|
||||
memoryLimit += stats.memoryLimit;
|
||||
networkRx += stats.networkRx;
|
||||
networkTx += stats.networkTx;
|
||||
blockRead += stats.blockRead;
|
||||
@@ -420,7 +418,6 @@
|
||||
let confirmDeleteName = $state<string | null>(null);
|
||||
let confirmStopName = $state<string | null>(null);
|
||||
let confirmDownName = $state<string | null>(null);
|
||||
let deleteVolumes = $state(false);
|
||||
|
||||
// Stack operation loading state
|
||||
let stackActionLoading = $state<string | null>(null);
|
||||
@@ -971,18 +968,15 @@
|
||||
|
||||
async function removeStack(name: string) {
|
||||
operationError = null;
|
||||
const withVolumes = deleteVolumes;
|
||||
deleteVolumes = false;
|
||||
try {
|
||||
const params = `force=true${withVolumes ? '&volumes=true' : ''}`;
|
||||
const response = await fetch(appendEnvParam(`/api/stacks/${encodeURIComponent(name)}?${params}`, envId), { method: 'DELETE' });
|
||||
const response = await fetch(appendEnvParam(`/api/stacks/${encodeURIComponent(name)}?force=true`, envId), { method: 'DELETE' });
|
||||
if (!response.ok) {
|
||||
const data = await response.json();
|
||||
const errorMsg = data.error || 'Failed to remove stack';
|
||||
showErrorDialog(`Failed to remove ${name}`, errorMsg);
|
||||
return;
|
||||
}
|
||||
toast.success(`Removed ${name}${withVolumes ? ' (volumes deleted)' : ''}`);
|
||||
toast.success(`Removed ${name}`);
|
||||
await fetchStacks();
|
||||
} catch (error) {
|
||||
console.error('Failed to remove stack:', error);
|
||||
@@ -1511,7 +1505,7 @@
|
||||
<button
|
||||
type="button"
|
||||
class="font-medium text-xs hover:text-primary hover:underline cursor-pointer text-left"
|
||||
onclick={(e) => { e.stopPropagation(); editStack(stack.name); }}
|
||||
onclick={() => editStack(stack.name)}
|
||||
>
|
||||
{stack.name}
|
||||
</button>
|
||||
@@ -1654,7 +1648,7 @@
|
||||
{@const stats = getStackStats(stack)}
|
||||
<div class="text-right">
|
||||
{#if stats}
|
||||
<span class="text-xs font-mono text-muted-foreground" title="{formatBytes(stats.memoryUsage)} / {formatBytes(stats.memoryLimit)}">{formatBytes(stats.memoryUsage)}<span class="text-muted-foreground/50">/{formatBytes(stats.memoryLimit, 0)}</span></span>
|
||||
<span class="text-xs font-mono text-muted-foreground" title="{formatBytes(stats.memoryUsage)} / {formatBytes(stats.memoryLimit)}">{formatBytes(stats.memoryUsage)}</span>
|
||||
{:else if stack.status === 'running' || stack.status === 'partial' || stack.status === 'restarting'}
|
||||
<span class="text-xs text-muted-foreground/50">...</span>
|
||||
{:else}
|
||||
@@ -1759,7 +1753,7 @@
|
||||
{#if source.sourceType === 'git' && source.gitStack}
|
||||
<button
|
||||
type="button"
|
||||
onclick={(e) => { e.stopPropagation(); openGitModal(source.gitStack); }}
|
||||
onclick={() => openGitModal(source.gitStack)}
|
||||
title="Edit git stack"
|
||||
class="p-1 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer"
|
||||
>
|
||||
@@ -1769,7 +1763,7 @@
|
||||
<!-- Internal stacks (including those needing file location) -->
|
||||
<button
|
||||
type="button"
|
||||
onclick={(e) => { e.stopPropagation(); editStack(stack.name); }}
|
||||
onclick={() => editStack(stack.name)}
|
||||
title="Edit"
|
||||
class="p-1 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer"
|
||||
>
|
||||
@@ -1780,7 +1774,7 @@
|
||||
{#if stack.containers && stack.containers.length > 0}
|
||||
<button
|
||||
type="button"
|
||||
onclick={(e) => { e.stopPropagation(); viewStackLogs(stack); }}
|
||||
onclick={() => viewStackLogs(stack)}
|
||||
title="View logs"
|
||||
class="p-1 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer"
|
||||
>
|
||||
@@ -1858,7 +1852,7 @@
|
||||
{#if $canAccess('stacks', 'start')}
|
||||
<button
|
||||
type="button"
|
||||
onclick={(e) => { e.stopPropagation(); startStack(stack.name); }}
|
||||
onclick={() => startStack(stack.name)}
|
||||
title="Start"
|
||||
class="p-1 rounded hover:bg-muted transition-colors opacity-70 hover:opacity-100 cursor-pointer"
|
||||
>
|
||||
@@ -1890,14 +1884,8 @@
|
||||
itemName={stack.name}
|
||||
title="Remove"
|
||||
onConfirm={() => removeStack(stack.name)}
|
||||
onOpenChange={(open) => { confirmDeleteName = open ? stack.name : null; if (!open) deleteVolumes = false; }}
|
||||
onOpenChange={(open) => confirmDeleteName = open ? stack.name : null}
|
||||
>
|
||||
{#snippet extraContent()}
|
||||
<label class="flex items-center gap-1.5 cursor-pointer">
|
||||
<Checkbox bind:checked={deleteVolumes} />
|
||||
<span class="text-xs text-muted-foreground">Also delete volumes</span>
|
||||
</label>
|
||||
{/snippet}
|
||||
{#snippet children({ open })}
|
||||
<Trash2 class="w-3 h-3 {open ? 'text-destructive' : 'text-muted-foreground hover:text-destructive'}" />
|
||||
{/snippet}
|
||||
@@ -2015,10 +2003,10 @@
|
||||
{/key}
|
||||
{/if}
|
||||
<div class="flex flex-wrap gap-1.5 mb-2 text-2xs">
|
||||
<!-- Clickable ports with range collapsing -->
|
||||
<!-- Clickable ports (dedupe by publicPort for IPv4/IPv6) -->
|
||||
{#if container.ports.length > 0}
|
||||
{@const mappedPorts = formatPorts(container.ports)}
|
||||
{#each mappedPorts as port}
|
||||
{@const uniquePorts = container.ports.filter((p, i, arr) => p.publicPort && arr.findIndex(x => x.publicPort === p.publicPort) === i)}
|
||||
{#each uniquePorts as port}
|
||||
{@const url = getPortUrl(port.publicPort)}
|
||||
{#if url}
|
||||
<a
|
||||
@@ -2029,12 +2017,12 @@
|
||||
class="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200 hover:bg-blue-200 dark:hover:bg-blue-800 transition-colors"
|
||||
title="Open {url} in new tab"
|
||||
>
|
||||
<code>{port.display}</code>
|
||||
<code>:{port.publicPort}</code>
|
||||
<ExternalLink class="w-2.5 h-2.5" />
|
||||
</a>
|
||||
{:else}
|
||||
<span class="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
|
||||
<code>{port.display}</code>
|
||||
<code>:{port.publicPort}</code>
|
||||
</span>
|
||||
{/if}
|
||||
{/each}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user