1.0.5
This commit is contained in:
1 parent
5475112806
commit
242f8df49d
35 files changed
+1892
-1987
No files matched your search
@@ -3,11 +3,51 @@
|
||||
import { EditorState, StateField, StateEffect, RangeSet } from '@codemirror/state';
|
||||
import { EditorView, keymap, lineNumbers, highlightActiveLine, highlightActiveLineGutter, gutter, GutterMarker, Decoration, WidgetType, type DecorationSet } from '@codemirror/view';
|
||||
import { defaultKeymap, history, historyKeymap, indentWithTab } from '@codemirror/commands';
|
||||
import { syntaxHighlighting, defaultHighlightStyle, indentOnInput, bracketMatching } from '@codemirror/language';
|
||||
import { syntaxHighlighting, defaultHighlightStyle, indentOnInput, bracketMatching, StreamLanguage, type StreamParser } from '@codemirror/language';
|
||||
import { searchKeymap, highlightSelectionMatches } from '@codemirror/search';
|
||||
import { autocompletion, completionKeymap, closeBrackets, closeBracketsKeymap, type CompletionContext, type CompletionResult } from '@codemirror/autocomplete';
|
||||
import { oneDarkHighlightStyle } from '@codemirror/theme-one-dark';
|
||||
|
||||
// Simple dotenv/env file language parser
|
||||
const dotenvParser: StreamParser<{ inValue: boolean }> = {
|
||||
startState() {
|
||||
return { inValue: false };
|
||||
},
|
||||
token(stream, state) {
|
||||
// Start of line
|
||||
if (stream.sol()) {
|
||||
state.inValue = false;
|
||||
// Skip leading whitespace
|
||||
stream.eatSpace();
|
||||
// Comment line
|
||||
if (stream.peek() === '#') {
|
||||
stream.skipToEnd();
|
||||
return 'comment';
|
||||
}
|
||||
}
|
||||
// If in value part, consume the rest
|
||||
if (state.inValue) {
|
||||
stream.skipToEnd();
|
||||
return 'string';
|
||||
}
|
||||
// Variable name before =
|
||||
if (stream.match(/^[a-zA-Z_][a-zA-Z0-9_]*/)) {
|
||||
if (stream.peek() === '=') {
|
||||
return 'variableName.definition';
|
||||
}
|
||||
return 'variableName';
|
||||
}
|
||||
// Equals sign - switch to value mode
|
||||
if (stream.eat('=')) {
|
||||
state.inValue = true;
|
||||
return 'operator';
|
||||
}
|
||||
// Skip anything else
|
||||
stream.next();
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// Docker Compose keywords for autocomplete
|
||||
const COMPOSE_TOP_LEVEL = ['services', 'networks', 'volumes', 'configs', 'secrets', 'name', 'version'];
|
||||
|
||||
@@ -453,6 +493,9 @@
|
||||
case 'sh':
|
||||
// No dedicated shell/dockerfile support, use basic highlighting
|
||||
return [];
|
||||
case 'dotenv':
|
||||
case 'env':
|
||||
return StreamLanguage.define(dotenvParser);
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
@@ -542,6 +585,13 @@
|
||||
// Track if we're initialized (prevents multiple createEditor calls)
|
||||
let initialized = false;
|
||||
|
||||
// Debounce timer for marker updates (prevents flicker during fast typing)
|
||||
let markerUpdateTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const MARKER_UPDATE_DEBOUNCE_MS = 300;
|
||||
|
||||
// Track last applied markers to avoid redundant updates
|
||||
let lastAppliedMarkersJson = '';
|
||||
|
||||
function createEditor() {
|
||||
if (!container || view || initialized) return;
|
||||
initialized = true;
|
||||
@@ -551,12 +601,14 @@
|
||||
: [dockhandLight, syntaxHighlighting(defaultHighlightStyle)];
|
||||
|
||||
// Build autocompletion config - add Docker Compose completions for YAML
|
||||
// Note: activateOnTyping can interfere with key repeat, so we disable it
|
||||
// Users can still trigger autocomplete manually with Ctrl+Space
|
||||
const autocompletionConfig = language === 'yaml'
|
||||
? autocompletion({
|
||||
override: [composeCompletions, composeValueCompletions],
|
||||
activateOnTyping: true
|
||||
activateOnTyping: false
|
||||
})
|
||||
: autocompletion();
|
||||
: autocompletion({ activateOnTyping: false });
|
||||
|
||||
const extensions = [
|
||||
lineNumbers(),
|
||||
@@ -594,18 +646,25 @@
|
||||
extensions
|
||||
});
|
||||
|
||||
// Custom transaction handler - this is SYNCHRONOUS and more reliable than updateListener
|
||||
// Custom transaction handler - applies transactions synchronously but defers callback
|
||||
// Based on the Svelte Playground pattern: https://svelte.dev/playground/91649ba3e0ce4122b3b34f3a95a00104
|
||||
const dispatchTransactions = (trs: readonly import('@codemirror/state').Transaction[]) => {
|
||||
if (!view) return;
|
||||
|
||||
// Apply all transactions
|
||||
// Apply all transactions synchronously (required by CodeMirror)
|
||||
view.update(trs);
|
||||
|
||||
// Check if any transaction changed the document
|
||||
const lastChangingTr = trs.findLast(tr => tr.docChanged);
|
||||
if (lastChangingTr && onchangeRef) {
|
||||
onchangeRef(lastChangingTr.newDoc.toString());
|
||||
// Defer callback to next microtask to avoid blocking input handling
|
||||
// This allows key repeat to work properly
|
||||
const newContent = lastChangingTr.newDoc.toString();
|
||||
queueMicrotask(() => {
|
||||
if (onchangeRef) {
|
||||
onchangeRef(newContent);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -615,7 +674,6 @@
|
||||
dispatchTransactions
|
||||
});
|
||||
|
||||
|
||||
// Push initial markers if provided
|
||||
if (variableMarkers.length > 0) {
|
||||
view.dispatch({
|
||||
@@ -625,11 +683,16 @@
|
||||
}
|
||||
|
||||
function destroyEditor() {
|
||||
if (markerUpdateTimer) {
|
||||
clearTimeout(markerUpdateTimer);
|
||||
markerUpdateTimer = null;
|
||||
}
|
||||
if (view) {
|
||||
view.destroy();
|
||||
view = null;
|
||||
}
|
||||
initialized = false;
|
||||
lastAppliedMarkersJson = '';
|
||||
}
|
||||
|
||||
// Get current editor content
|
||||
@@ -656,11 +719,35 @@
|
||||
}
|
||||
|
||||
// Update variable markers - this is the key method for parent to call
|
||||
export function updateVariableMarkers(markers: VariableMarker[]) {
|
||||
if (view) {
|
||||
view.dispatch({
|
||||
effects: updateMarkersEffect.of(markers)
|
||||
});
|
||||
// Debounced to prevent flicker during fast typing
|
||||
export function updateVariableMarkers(markers: VariableMarker[], immediate = false) {
|
||||
if (!view) return;
|
||||
|
||||
// Check if markers actually changed (compare by content, not reference)
|
||||
const newJson = JSON.stringify(markers);
|
||||
if (newJson === lastAppliedMarkersJson) {
|
||||
return; // No change, skip update
|
||||
}
|
||||
|
||||
// Clear any pending update
|
||||
if (markerUpdateTimer) {
|
||||
clearTimeout(markerUpdateTimer);
|
||||
markerUpdateTimer = null;
|
||||
}
|
||||
|
||||
const applyUpdate = () => {
|
||||
if (view) {
|
||||
lastAppliedMarkersJson = newJson;
|
||||
view.dispatch({
|
||||
effects: updateMarkersEffect.of(markers)
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
if (immediate) {
|
||||
applyUpdate();
|
||||
} else {
|
||||
markerUpdateTimer = setTimeout(applyUpdate, MARKER_UPDATE_DEBOUNCE_MS);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -693,12 +780,11 @@
|
||||
});
|
||||
|
||||
// Update markers when prop changes (backup mechanism, parent should also call updateVariableMarkers)
|
||||
// Uses the debounced update to prevent flicker during fast typing
|
||||
$effect(() => {
|
||||
const markers = variableMarkers;
|
||||
if (view && markers) {
|
||||
view.dispatch({
|
||||
effects: updateMarkersEffect.of(markers)
|
||||
});
|
||||
updateVariableMarkers(markers);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@@ -706,7 +792,6 @@
|
||||
<div
|
||||
bind:this={container}
|
||||
class="h-full w-full overflow-hidden {className}"
|
||||
onkeydown={(e) => e.stopPropagation()}
|
||||
></div>
|
||||
|
||||
<style>
|
||||
|
||||
@@ -46,6 +46,8 @@
|
||||
let status = $state<PullStatus>('idle');
|
||||
let image = $state(initialImageName);
|
||||
let duration = $state(0);
|
||||
// Track whether image was set from initial prop vs typed by user
|
||||
let hasAutoStarted = $state(false);
|
||||
|
||||
// Notify parent of status changes
|
||||
$effect(() => {
|
||||
@@ -82,8 +84,10 @@
|
||||
onImageChange?.(image);
|
||||
});
|
||||
|
||||
// Auto-start only once for prefilled images, not when user is typing
|
||||
$effect(() => {
|
||||
if (autoStart && image && status === 'idle') {
|
||||
if (autoStart && initialImageName && image === initialImageName && status === 'idle' && !hasAutoStarted) {
|
||||
hasAutoStarted = true;
|
||||
startPull();
|
||||
}
|
||||
});
|
||||
@@ -133,6 +137,7 @@
|
||||
layerOrder = 0;
|
||||
outputLines = [];
|
||||
duration = 0;
|
||||
hasAutoStarted = false;
|
||||
}
|
||||
|
||||
export function getImage() {
|
||||
|
||||
@@ -99,7 +99,7 @@
|
||||
<div class="space-y-3">
|
||||
<!-- Variables List -->
|
||||
<div class="space-y-3">
|
||||
{#each variables as variable, index}
|
||||
{#each variables as variable, index (index)}
|
||||
{@const source = getSource(variable.key)}
|
||||
{@const isVarRequired = isRequired(variable.key)}
|
||||
{@const isVarOptional = isOptional(variable.key)}
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
<script lang="ts">
|
||||
import { tick, untrack } from 'svelte';
|
||||
import { Button } from '$lib/components/ui/button';
|
||||
import StackEnvVarsEditor, { type EnvVar, type ValidationResult } from '$lib/components/StackEnvVarsEditor.svelte';
|
||||
import CodeEditor from '$lib/components/CodeEditor.svelte';
|
||||
import ConfirmPopover from '$lib/components/ConfirmPopover.svelte';
|
||||
import { Plus, Info, Upload, Trash2 } from 'lucide-svelte';
|
||||
import { Plus, Info, Upload, Trash2, List, FileText, AlertTriangle } from 'lucide-svelte';
|
||||
import * as Tooltip from '$lib/components/ui/tooltip';
|
||||
|
||||
interface Props {
|
||||
variables: EnvVar[];
|
||||
variables: EnvVar[]; // Bindable - kept in sync with rawContent
|
||||
rawContent?: string; // The actual content saved to disk - source of truth
|
||||
validation?: ValidationResult | null;
|
||||
readonly?: boolean;
|
||||
showSource?: boolean;
|
||||
@@ -19,7 +22,8 @@
|
||||
}
|
||||
|
||||
let {
|
||||
variables = $bindable(),
|
||||
variables = $bindable([]),
|
||||
rawContent = $bindable(''),
|
||||
validation = null,
|
||||
readonly = false,
|
||||
showSource = false,
|
||||
@@ -31,44 +35,194 @@
|
||||
onchange
|
||||
}: Props = $props();
|
||||
|
||||
const STORAGE_KEY_VIEW_MODE = 'dockhand-env-vars-view-mode';
|
||||
|
||||
let fileInputRef: HTMLInputElement;
|
||||
let viewMode = $state<'form' | 'text'>(
|
||||
(typeof localStorage !== 'undefined' && localStorage.getItem(STORAGE_KEY_VIEW_MODE) as 'form' | 'text') || 'form'
|
||||
);
|
||||
let confirmClearOpen = $state(false);
|
||||
let contentAreaRef: HTMLDivElement;
|
||||
let parseWarnings = $state<string[]>([]);
|
||||
let editorTheme = $state<'light' | 'dark'>('dark');
|
||||
|
||||
function addEnvVariable() {
|
||||
variables = [...variables, { key: '', value: '', isSecret: false }];
|
||||
}
|
||||
// Track previous variables to detect form changes
|
||||
let prevVariablesJson = $state('');
|
||||
|
||||
function handleLoadFromFile() {
|
||||
fileInputRef?.click();
|
||||
}
|
||||
// Track if initial sync has been done (to distinguish initial load from user action)
|
||||
let initialized = $state(false);
|
||||
|
||||
function parseEnvFile(content: string): EnvVar[] {
|
||||
const lines = content.split('\n');
|
||||
const envVars: EnvVar[] = [];
|
||||
// Parse raw content to EnvVar array
|
||||
function parseRawContent(content: string): { vars: EnvVar[], warnings: string[] } {
|
||||
const result: EnvVar[] = [];
|
||||
const warnings: string[] = [];
|
||||
let lineNum = 0;
|
||||
|
||||
for (const line of lines) {
|
||||
// Skip empty lines and comments
|
||||
for (const line of content.split('\n')) {
|
||||
lineNum++;
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('#')) continue;
|
||||
|
||||
// Parse KEY=VALUE format
|
||||
const eqIndex = trimmed.indexOf('=');
|
||||
if (eqIndex === -1) continue;
|
||||
if (eqIndex === -1) {
|
||||
warnings.push(`Line ${lineNum}: "${trimmed.slice(0, 30)}${trimmed.length > 30 ? '...' : ''}" (no = found)`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const key = trimmed.slice(0, eqIndex).trim();
|
||||
let value = trimmed.slice(eqIndex + 1).trim();
|
||||
let value = trimmed.slice(eqIndex + 1);
|
||||
|
||||
// Remove surrounding quotes if present
|
||||
if ((value.startsWith('"') && value.endsWith('"')) ||
|
||||
(value.startsWith("'") && value.endsWith("'"))) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
|
||||
if (key) {
|
||||
envVars.push({ key, value, isSecret: false });
|
||||
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
|
||||
warnings.push(`Line ${lineNum}: "${key}" (invalid variable name)`);
|
||||
continue;
|
||||
}
|
||||
result.push({
|
||||
key,
|
||||
value,
|
||||
isSecret: existingSecretKeys.has(key) || false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return envVars;
|
||||
return { vars: result, warnings };
|
||||
}
|
||||
|
||||
// Update rawContent when variables change - replace var lines by position, preserve comments
|
||||
function syncRawContentFromVariables(newVars: EnvVar[]) {
|
||||
const lines = rawContent.split('\n');
|
||||
const resultLines: string[] = [];
|
||||
const varsWithKeys = newVars.filter(v => v.key.trim());
|
||||
let varIdx = 0;
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
// Keep comments and blank lines
|
||||
if (!trimmed || trimmed.startsWith('#')) {
|
||||
resultLines.push(line);
|
||||
continue;
|
||||
}
|
||||
|
||||
const eqIndex = trimmed.indexOf('=');
|
||||
if (eqIndex > 0) {
|
||||
const key = trimmed.slice(0, eqIndex).trim();
|
||||
if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) {
|
||||
// This is a valid variable line - replace with var at current index
|
||||
if (varIdx < varsWithKeys.length) {
|
||||
const v = varsWithKeys[varIdx];
|
||||
resultLines.push(`${v.key.trim()}=${v.value}`);
|
||||
varIdx++;
|
||||
}
|
||||
// If we have fewer vars, this line is deleted
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// Keep invalid lines as-is
|
||||
resultLines.push(line);
|
||||
}
|
||||
|
||||
// Append any new variables
|
||||
while (varIdx < varsWithKeys.length) {
|
||||
const v = varsWithKeys[varIdx];
|
||||
resultLines.push(`${v.key.trim()}=${v.value}`);
|
||||
varIdx++;
|
||||
}
|
||||
|
||||
let result = resultLines.join('\n');
|
||||
if (result && !result.endsWith('\n')) {
|
||||
result += '\n';
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// When rawContent changes externally (text view, file load), update variables
|
||||
$effect(() => {
|
||||
const { vars, warnings } = parseRawContent(rawContent);
|
||||
parseWarnings = warnings;
|
||||
|
||||
// Initial load with no .env file: don't overwrite DB-loaded variables
|
||||
// Let the second $effect generate rawContent from the existing variables instead
|
||||
if (!initialized && !rawContent.trim() && variables.length > 0) {
|
||||
initialized = true;
|
||||
return;
|
||||
}
|
||||
initialized = true;
|
||||
|
||||
// When rawContent has content, merge parsed vars with existing DB secrets
|
||||
// This handles the case where .env file exists but DB has additional secrets
|
||||
let finalVars = vars;
|
||||
if (rawContent.trim()) {
|
||||
const parsedKeys = new Set(vars.map(v => v.key));
|
||||
const existingSecrets = untrack(() =>
|
||||
variables.filter(v => v.isSecret && !parsedKeys.has(v.key))
|
||||
);
|
||||
if (existingSecrets.length > 0) {
|
||||
finalVars = [...vars, ...existingSecrets];
|
||||
}
|
||||
}
|
||||
|
||||
const newJson = JSON.stringify(finalVars.map(v => ({ key: v.key, value: v.value })));
|
||||
// Use untrack to read variables without creating a dependency on it
|
||||
// This prevents the effect from running when variables changes (only rawContent should trigger it)
|
||||
const currentNonEmptyJson = untrack(() =>
|
||||
JSON.stringify(variables.filter(v => v.key.trim()).map(v => ({ key: v.key, value: v.value })))
|
||||
);
|
||||
|
||||
if (newJson !== currentNonEmptyJson) {
|
||||
variables = finalVars;
|
||||
prevVariablesJson = newJson;
|
||||
}
|
||||
});
|
||||
|
||||
// When variables change from form edits, update rawContent
|
||||
$effect(() => {
|
||||
const currentJson = JSON.stringify(variables.map(v => ({ key: v.key, value: v.value })));
|
||||
|
||||
// Only sync if variables actually changed (not from parsing rawContent)
|
||||
if (currentJson !== prevVariablesJson) {
|
||||
prevVariablesJson = currentJson;
|
||||
const newRaw = syncRawContentFromVariables(variables);
|
||||
if (newRaw !== rawContent) {
|
||||
rawContent = newRaw;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function handleTextChange(value: string) {
|
||||
rawContent = value;
|
||||
onchange?.();
|
||||
}
|
||||
|
||||
function handleViewModeChange(newMode: 'form' | 'text') {
|
||||
viewMode = newMode;
|
||||
localStorage.setItem(STORAGE_KEY_VIEW_MODE, newMode);
|
||||
}
|
||||
|
||||
async function addEnvVariable() {
|
||||
variables = [...variables, { key: '', value: '', isSecret: false }];
|
||||
onchange?.();
|
||||
await tick();
|
||||
if (contentAreaRef) {
|
||||
contentAreaRef.scrollTop = contentAreaRef.scrollHeight;
|
||||
}
|
||||
}
|
||||
|
||||
async function addMissingVariable(key: string) {
|
||||
variables = [...variables, { key, value: '', isSecret: false }];
|
||||
onchange?.();
|
||||
await tick();
|
||||
if (contentAreaRef) {
|
||||
contentAreaRef.scrollTop = contentAreaRef.scrollHeight;
|
||||
}
|
||||
}
|
||||
|
||||
function handleLoadFromFile() {
|
||||
fileInputRef?.click();
|
||||
}
|
||||
|
||||
function handleFileSelect(event: Event) {
|
||||
@@ -78,90 +232,90 @@
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
const content = e.target?.result as string;
|
||||
const parsedVars = parseEnvFile(content);
|
||||
|
||||
if (parsedVars.length > 0) {
|
||||
// Get existing keys to avoid duplicates
|
||||
const existingKeys = new Set(variables.filter(v => v.key.trim()).map(v => v.key.trim()));
|
||||
|
||||
// Filter empty entries from current variables
|
||||
const nonEmptyVars = variables.filter(v => v.key.trim());
|
||||
|
||||
// Add new variables, updating existing ones or appending new
|
||||
for (const newVar of parsedVars) {
|
||||
if (existingKeys.has(newVar.key)) {
|
||||
// Update existing variable
|
||||
const idx = nonEmptyVars.findIndex(v => v.key.trim() === newVar.key);
|
||||
if (idx !== -1) {
|
||||
nonEmptyVars[idx] = { ...nonEmptyVars[idx], value: newVar.value };
|
||||
}
|
||||
} else {
|
||||
// Add new variable
|
||||
nonEmptyVars.push(newVar);
|
||||
existingKeys.add(newVar.key);
|
||||
}
|
||||
}
|
||||
|
||||
variables = nonEmptyVars;
|
||||
// Notify parent of change (important for async file load)
|
||||
onchange?.();
|
||||
}
|
||||
rawContent = e.target?.result as string;
|
||||
onchange?.();
|
||||
};
|
||||
reader.readAsText(file);
|
||||
|
||||
// Reset input so the same file can be selected again
|
||||
input.value = '';
|
||||
}
|
||||
|
||||
function clearAllVariables() {
|
||||
function clearAll() {
|
||||
rawContent = '';
|
||||
variables = [];
|
||||
onchange?.();
|
||||
}
|
||||
|
||||
// Count of non-empty variables
|
||||
const hasVariables = $derived(variables.some(v => v.key.trim()));
|
||||
const hasContent = $derived(!!rawContent?.trim() || variables.some(v => v.key.trim()));
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full {className}">
|
||||
<!-- Header -->
|
||||
<div class="px-4 py-2.5 border-b border-zinc-200 dark:border-zinc-700 flex flex-col gap-1.5">
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<div class="flex items-center gap-2 flex-nowrap min-w-0">
|
||||
<span class="text-xs text-zinc-500 dark:text-zinc-400">Environment variables</span>
|
||||
{#if infoText}
|
||||
<Tooltip.Root>
|
||||
<Tooltip.Trigger>
|
||||
<Info class="w-3.5 h-3.5 text-blue-400" />
|
||||
</Tooltip.Trigger>
|
||||
<Tooltip.Content class="max-w-md">
|
||||
<p class="text-xs">{infoText}</p>
|
||||
</Tooltip.Content>
|
||||
<Tooltip.Portal>
|
||||
<Tooltip.Content side="bottom" sideOffset={8} class="max-w-xs w-64 bg-white dark:bg-zinc-900 text-zinc-900 dark:text-zinc-100 border-zinc-200 dark:border-zinc-700">
|
||||
<p class="text-xs text-left">{infoText}</p>
|
||||
</Tooltip.Content>
|
||||
</Tooltip.Portal>
|
||||
</Tooltip.Root>
|
||||
{/if}
|
||||
<!-- View mode toggle -->
|
||||
<div class="flex items-center gap-0.5 bg-zinc-100 dark:bg-zinc-800 rounded p-0.5 ml-1">
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-1 px-1.5 py-0.5 rounded text-2xs transition-colors {viewMode === 'form' ? 'bg-white dark:bg-zinc-700 text-zinc-800 dark:text-zinc-100 shadow-sm' : 'text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200'}"
|
||||
onclick={() => handleViewModeChange('form')}
|
||||
title="Form view"
|
||||
>
|
||||
<List class="w-3 h-3" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex items-center gap-1 px-1.5 py-0.5 rounded text-2xs transition-colors {viewMode === 'text' ? 'bg-white dark:bg-zinc-700 text-zinc-800 dark:text-zinc-100 shadow-sm' : 'text-zinc-500 dark:text-zinc-400 hover:text-zinc-700 dark:hover:text-zinc-200'}"
|
||||
onclick={() => handleViewModeChange('text')}
|
||||
title="Text view (raw .env file)"
|
||||
>
|
||||
<FileText class="w-3 h-3" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{#if !readonly}
|
||||
<div class="flex items-center gap-1">
|
||||
<div class="flex items-center gap-1 shrink-0 ml-4">
|
||||
<Button type="button" size="sm" variant="ghost" onclick={handleLoadFromFile} class="h-6 text-xs px-2">
|
||||
<Upload class="w-3.5 h-3.5 mr-1" />
|
||||
Load .env
|
||||
</Button>
|
||||
<Button type="button" size="sm" variant="ghost" onclick={addEnvVariable} class="h-6 text-xs px-2">
|
||||
<Plus class="w-3.5 h-3.5 mr-1" />
|
||||
Add
|
||||
</Button>
|
||||
{#if hasVariables}
|
||||
<ConfirmPopover
|
||||
title="Clear all variables"
|
||||
description="This will remove all environment variables. This cannot be undone."
|
||||
confirmText="Clear all"
|
||||
onConfirm={clearAllVariables}
|
||||
>
|
||||
<Button type="button" size="sm" variant="ghost" class="h-6 text-xs px-2 text-destructive hover:text-destructive">
|
||||
<Trash2 class="w-3.5 h-3.5 mr-1" />
|
||||
Clear
|
||||
</Button>
|
||||
</ConfirmPopover>
|
||||
{#if viewMode === 'form'}
|
||||
<Button type="button" size="sm" variant="ghost" onclick={addEnvVariable} class="h-6 text-xs px-2">
|
||||
<Plus class="w-3.5 h-3.5 mr-1" />
|
||||
Add
|
||||
</Button>
|
||||
{/if}
|
||||
<div class="{hasContent ? '' : 'invisible'}">
|
||||
<ConfirmPopover
|
||||
bind:open={confirmClearOpen}
|
||||
title="Clear all variables?"
|
||||
action="clear"
|
||||
itemType="environment variables"
|
||||
confirmText="Clear all"
|
||||
onConfirm={clearAll}
|
||||
onOpenChange={(o) => confirmClearOpen = o}
|
||||
>
|
||||
{#snippet children({ open })}
|
||||
<Button type="button" size="sm" variant="ghost" class="h-6 text-xs px-2 text-destructive hover:text-destructive">
|
||||
<Trash2 class="w-3.5 h-3.5 mr-1" />
|
||||
Clear
|
||||
</Button>
|
||||
{/snippet}
|
||||
</ConfirmPopover>
|
||||
</div>
|
||||
</div>
|
||||
<input
|
||||
bind:this={fileInputRef}
|
||||
@@ -172,47 +326,44 @@
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
<!-- Variable syntax help -->
|
||||
<div class="flex flex-wrap gap-x-3 gap-y-0.5 text-2xs text-zinc-400 dark:text-zinc-500 font-mono">
|
||||
<span><span class="text-zinc-500 dark:text-zinc-400">${`{VAR}`}</span> required</span>
|
||||
<span><span class="text-zinc-500 dark:text-zinc-400">${`{VAR:-default}`}</span> optional</span>
|
||||
<span><span class="text-zinc-500 dark:text-zinc-400">${`{VAR:?error}`}</span> required w/ error</span>
|
||||
</div>
|
||||
<!-- Validation status pills -->
|
||||
{#if validation}
|
||||
<div class="flex flex-wrap gap-1">
|
||||
{#if validation.missing.length > 0}
|
||||
<span class="inline-flex items-center px-1.5 py-0.5 rounded text-2xs font-medium bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300">
|
||||
{validation.missing.length} missing
|
||||
</span>
|
||||
{/if}
|
||||
{#if validation.required.length > 0}
|
||||
<span class="inline-flex items-center px-1.5 py-0.5 rounded text-2xs font-medium bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300">
|
||||
{validation.required.length - validation.missing.length} required
|
||||
</span>
|
||||
{/if}
|
||||
{#if validation.optional.length > 0}
|
||||
<span class="inline-flex items-center px-1.5 py-0.5 rounded text-2xs font-medium bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300">
|
||||
{validation.optional.length} optional
|
||||
</span>
|
||||
{/if}
|
||||
{#if validation.unused.length > 0}
|
||||
<span class="inline-flex items-center px-1.5 py-0.5 rounded text-2xs font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300">
|
||||
{validation.unused.length} unused
|
||||
</span>
|
||||
{/if}
|
||||
<!-- Help text -->
|
||||
{#if viewMode === 'form'}
|
||||
<div class="flex flex-wrap gap-x-3 gap-y-0.5 text-2xs text-zinc-400 dark:text-zinc-500 font-mono">
|
||||
<span><span class="text-zinc-500 dark:text-zinc-400">${`{VAR}`}</span> required</span>
|
||||
<span><span class="text-zinc-500 dark:text-zinc-400">${`{VAR:-default}`}</span> optional</span>
|
||||
<span><span class="text-zinc-500 dark:text-zinc-400">${`{VAR:?error}`}</span> required w/ error</span>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="text-2xs text-zinc-400 dark:text-zinc-500">
|
||||
Raw .env file (comments preserved, saved exactly as typed)
|
||||
</div>
|
||||
{/if}
|
||||
<!-- Add missing variables -->
|
||||
{#if validation && validation.missing.length > 0 && !readonly}
|
||||
<!-- Parse warnings (form mode only) -->
|
||||
{#if viewMode === 'form' && parseWarnings.length > 0}
|
||||
<div class="flex items-start gap-2 px-2 py-1.5 rounded bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800/50">
|
||||
<AlertTriangle class="w-3.5 h-3.5 text-amber-500 shrink-0 mt-0.5" />
|
||||
<div class="text-2xs text-amber-700 dark:text-amber-300">
|
||||
<span class="font-medium">Some lines couldn't be parsed:</span>
|
||||
<ul class="mt-0.5 list-disc list-inside">
|
||||
{#each parseWarnings.slice(0, 3) as warning}
|
||||
<li>{warning}</li>
|
||||
{/each}
|
||||
{#if parseWarnings.length > 3}
|
||||
<li>...and {parseWarnings.length - 3} more</li>
|
||||
{/if}
|
||||
</ul>
|
||||
<p class="mt-1 text-amber-600 dark:text-amber-400">Switch to text view to edit these lines.</p>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<!-- Add missing variables (form mode only) -->
|
||||
{#if viewMode === 'form' && validation && validation.missing.length > 0 && !readonly}
|
||||
<div class="flex flex-wrap gap-1 items-center">
|
||||
<span class="text-xs text-muted-foreground mr-1">Add missing:</span>
|
||||
{#each validation.missing as missing}
|
||||
<button
|
||||
type="button"
|
||||
onclick={() => {
|
||||
variables = [...variables, { key: missing, value: '', isSecret: false }];
|
||||
}}
|
||||
onclick={() => addMissingVariable(missing)}
|
||||
class="text-xs px-1.5 py-0.5 rounded bg-red-100 text-red-700 hover:bg-red-200 dark:bg-red-900/30 dark:text-red-300 dark:hover:bg-red-900/50 transition-colors"
|
||||
>
|
||||
{missing}
|
||||
@@ -221,16 +372,27 @@
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
<!-- Variables list -->
|
||||
<div class="flex-1 overflow-auto px-4 py-3">
|
||||
<StackEnvVarsEditor
|
||||
bind:variables
|
||||
{validation}
|
||||
{readonly}
|
||||
{showSource}
|
||||
{sources}
|
||||
{placeholder}
|
||||
{existingSecretKeys}
|
||||
/>
|
||||
<!-- Content area -->
|
||||
<div bind:this={contentAreaRef} class="flex-1 overflow-auto px-4 py-3">
|
||||
{#if viewMode === 'form'}
|
||||
<StackEnvVarsEditor
|
||||
bind:variables
|
||||
{validation}
|
||||
{readonly}
|
||||
{showSource}
|
||||
{sources}
|
||||
{placeholder}
|
||||
{existingSecretKeys}
|
||||
/>
|
||||
{:else}
|
||||
<CodeEditor
|
||||
value={rawContent}
|
||||
language="dotenv"
|
||||
theme={editorTheme}
|
||||
readonly={readonly}
|
||||
onchange={handleTextChange}
|
||||
class="h-full min-h-[200px] rounded-md overflow-hidden border border-zinc-200 dark:border-zinc-700"
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,4 +1,24 @@
|
||||
[
|
||||
{
|
||||
"version": "1.0.5",
|
||||
"date": "2026-01-01",
|
||||
"changes": [
|
||||
{ "type": "feature", "text": "Clicking container name opens container details" },
|
||||
{ "type": "feature", "text": "Clicking stack name opens stack editor (internal stacks)" },
|
||||
{ "type": "feature", "text": "Stack env editor now supports freestyle text entry for pasting env contents" },
|
||||
{ "type": "feature", "text": "Stack env vars saved as .env file next to compose, respecting external edits" },
|
||||
{ "type": "feature", "text": "Additional container options: ulimits, security options, DNS settings" },
|
||||
{ "type": "fix", "text": "More detailed error messages when stack fails to start" },
|
||||
{ "type": "fix", "text": "Container startup with user: directive in compose" },
|
||||
{ "type": "fix", "text": "Stack editor flickering when typing fast" },
|
||||
{ "type": "fix", "text": "Container unhealthy notifications not triggering" },
|
||||
{ "type": "fix", "text": "tlsSkipVerify not being saved in environment settings" },
|
||||
{ "type": "fix", "text": "MFA available to all users without enterprise license" },
|
||||
{ "type": "fix", "text": "Socket proxy documentation and examples" },
|
||||
{ "type": "fix", "text": "Edit container modal reloading during editing" }
|
||||
],
|
||||
"imageTag": "fnsys/dockhand:v1.0.5"
|
||||
},
|
||||
{
|
||||
"version": "1.0.4",
|
||||
"date": "2025-12-28",
|
||||
|
||||
+116
-13
@@ -747,12 +747,70 @@ function getAttributeValue(entry: any, attribute: string): string | undefined {
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// MFA (TOTP)
|
||||
// MFA (TOTP) with Backup Codes
|
||||
// ============================================
|
||||
|
||||
import * as OTPAuth from 'otpauth';
|
||||
import * as QRCode from 'qrcode';
|
||||
|
||||
// MFA data stored in mfaSecret field as JSON
|
||||
interface MfaData {
|
||||
secret: string; // TOTP secret (base32)
|
||||
backupCodes: string[]; // Hashed backup codes (unused ones)
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate 10 random backup codes (8 characters each, alphanumeric)
|
||||
*/
|
||||
function generateBackupCodes(): string[] {
|
||||
const codes: string[] = [];
|
||||
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // Removed confusable chars: 0, O, 1, I
|
||||
for (let i = 0; i < 10; i++) {
|
||||
let code = '';
|
||||
for (let j = 0; j < 8; j++) {
|
||||
code += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
codes.push(code);
|
||||
}
|
||||
return codes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hash a backup code for storage
|
||||
*/
|
||||
async function hashBackupCode(code: string): Promise<string> {
|
||||
// Normalize: uppercase, remove spaces and dashes
|
||||
const normalized = code.toUpperCase().replace(/[\s-]/g, '');
|
||||
const hasher = new Bun.CryptoHasher('sha256');
|
||||
hasher.update(normalized);
|
||||
return hasher.digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse MFA data from database field
|
||||
*/
|
||||
function parseMfaData(mfaSecret: string | null | undefined): MfaData | null {
|
||||
if (!mfaSecret) return null;
|
||||
|
||||
try {
|
||||
// Try parsing as JSON first (new format)
|
||||
const parsed = JSON.parse(mfaSecret);
|
||||
if (parsed && typeof parsed.secret === 'string') {
|
||||
return {
|
||||
secret: parsed.secret,
|
||||
backupCodes: parsed.backupCodes || []
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
// Legacy format: plain base32 secret string
|
||||
return {
|
||||
secret: mfaSecret,
|
||||
backupCodes: []
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate MFA secret and QR code for setup
|
||||
*/
|
||||
@@ -787,18 +845,24 @@ export async function generateMfaSetup(userId: number): Promise<{
|
||||
margin: 2
|
||||
});
|
||||
|
||||
// Store secret temporarily (user must verify before it's enabled)
|
||||
await updateUser(userId, { mfaSecret: secretBase32 });
|
||||
// Store secret temporarily as JSON (user must verify before it's enabled)
|
||||
// Backup codes will be generated after verification
|
||||
const mfaData: MfaData = { secret: secretBase32, backupCodes: [] };
|
||||
await updateUser(userId, { mfaSecret: JSON.stringify(mfaData) });
|
||||
|
||||
return { secret: secretBase32, qrDataUrl };
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify MFA token and enable MFA if valid
|
||||
* Returns backup codes on success (shown only once)
|
||||
*/
|
||||
export async function verifyAndEnableMfa(userId: number, token: string): Promise<boolean> {
|
||||
export async function verifyAndEnableMfa(userId: number, token: string): Promise<{ success: false } | { success: true; backupCodes: string[] }> {
|
||||
const user = await getUser(userId);
|
||||
if (!user || !user.mfaSecret) return false;
|
||||
if (!user || !user.mfaSecret) return { success: false };
|
||||
|
||||
const mfaData = parseMfaData(user.mfaSecret);
|
||||
if (!mfaData) return { success: false };
|
||||
|
||||
const totp = new OTPAuth.TOTP({
|
||||
issuer: 'Dockhand',
|
||||
@@ -806,35 +870,74 @@ export async function verifyAndEnableMfa(userId: number, token: string): Promise
|
||||
algorithm: 'SHA1',
|
||||
digits: 6,
|
||||
period: 30,
|
||||
secret: OTPAuth.Secret.fromBase32(user.mfaSecret)
|
||||
secret: OTPAuth.Secret.fromBase32(mfaData.secret)
|
||||
});
|
||||
|
||||
const delta = totp.validate({ token, window: 1 });
|
||||
if (delta === null) return false;
|
||||
if (delta === null) return { success: false };
|
||||
|
||||
// Enable MFA
|
||||
await updateUser(userId, { mfaEnabled: true });
|
||||
return true;
|
||||
// Generate backup codes
|
||||
const plainBackupCodes = generateBackupCodes();
|
||||
const hashedBackupCodes = await Promise.all(plainBackupCodes.map(hashBackupCode));
|
||||
|
||||
// Update MFA data with hashed backup codes and enable MFA
|
||||
const updatedMfaData: MfaData = {
|
||||
secret: mfaData.secret,
|
||||
backupCodes: hashedBackupCodes
|
||||
};
|
||||
await updateUser(userId, {
|
||||
mfaEnabled: true,
|
||||
mfaSecret: JSON.stringify(updatedMfaData)
|
||||
});
|
||||
|
||||
// Return plain backup codes (shown only once)
|
||||
return { success: true, backupCodes: plainBackupCodes };
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify MFA token during login
|
||||
* Verify MFA token during login (accepts TOTP code or backup code)
|
||||
*/
|
||||
export async function verifyMfaToken(userId: number, token: string): Promise<boolean> {
|
||||
const user = await getUser(userId);
|
||||
if (!user || !user.mfaEnabled || !user.mfaSecret) return false;
|
||||
|
||||
const mfaData = parseMfaData(user.mfaSecret);
|
||||
if (!mfaData) return false;
|
||||
|
||||
// First, try TOTP verification
|
||||
const totp = new OTPAuth.TOTP({
|
||||
issuer: 'Dockhand',
|
||||
label: user.username,
|
||||
algorithm: 'SHA1',
|
||||
digits: 6,
|
||||
period: 30,
|
||||
secret: OTPAuth.Secret.fromBase32(user.mfaSecret)
|
||||
secret: OTPAuth.Secret.fromBase32(mfaData.secret)
|
||||
});
|
||||
|
||||
const delta = totp.validate({ token, window: 1 });
|
||||
return delta !== null;
|
||||
if (delta !== null) return true;
|
||||
|
||||
// If TOTP fails, try backup code
|
||||
if (mfaData.backupCodes && mfaData.backupCodes.length > 0) {
|
||||
const hashedInput = await hashBackupCode(token);
|
||||
const codeIndex = mfaData.backupCodes.indexOf(hashedInput);
|
||||
|
||||
if (codeIndex !== -1) {
|
||||
// Remove used backup code
|
||||
const updatedBackupCodes = [...mfaData.backupCodes];
|
||||
updatedBackupCodes.splice(codeIndex, 1);
|
||||
|
||||
const updatedMfaData: MfaData = {
|
||||
secret: mfaData.secret,
|
||||
backupCodes: updatedBackupCodes
|
||||
};
|
||||
await updateUser(userId, { mfaSecret: JSON.stringify(updatedMfaData) });
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -156,6 +156,7 @@ export async function updateEnvironment(id: number, env: Partial<Environment>):
|
||||
if (env.tlsCa !== undefined) updateData.tlsCa = env.tlsCa;
|
||||
if (env.tlsCert !== undefined) updateData.tlsCert = env.tlsCert;
|
||||
if (env.tlsKey !== undefined) updateData.tlsKey = env.tlsKey;
|
||||
if (env.tlsSkipVerify !== undefined) updateData.tlsSkipVerify = env.tlsSkipVerify;
|
||||
if (env.icon !== undefined) updateData.icon = env.icon;
|
||||
if (env.socketPath !== undefined) updateData.socketPath = env.socketPath;
|
||||
if (env.collectActivity !== undefined) updateData.collectActivity = env.collectActivity;
|
||||
@@ -808,6 +809,7 @@ export interface SmtpConfig {
|
||||
from_email: string;
|
||||
from_name?: string;
|
||||
to_emails: string[];
|
||||
skipTlsVerify?: boolean; // Skip TLS certificate verification (useful for self-signed certs)
|
||||
}
|
||||
|
||||
export interface AppriseConfig {
|
||||
|
||||
@@ -181,7 +181,7 @@ export const users = sqliteTable('users', {
|
||||
avatar: text('avatar'),
|
||||
authProvider: text('auth_provider').default('local'), // e.g., 'local', 'oidc:Keycloak', 'ldap:AD'
|
||||
mfaEnabled: integer('mfa_enabled', { mode: 'boolean' }).default(false),
|
||||
mfaSecret: text('mfa_secret'),
|
||||
mfaSecret: text('mfa_secret'), // JSON: { secret: string, backupCodes: string[] }
|
||||
isActive: integer('is_active', { mode: 'boolean' }).default(true),
|
||||
lastLogin: text('last_login'),
|
||||
createdAt: text('created_at').default(sql`CURRENT_TIMESTAMP`),
|
||||
|
||||
@@ -184,7 +184,7 @@ export const users = pgTable('users', {
|
||||
avatar: text('avatar'),
|
||||
authProvider: text('auth_provider').default('local'), // e.g., 'local', 'oidc:Keycloak', 'ldap:AD'
|
||||
mfaEnabled: boolean('mfa_enabled').default(false),
|
||||
mfaSecret: text('mfa_secret'),
|
||||
mfaSecret: text('mfa_secret'), // JSON: { secret: string, backupCodes: string[] }
|
||||
isActive: boolean('is_active').default(true),
|
||||
lastLogin: timestamp('last_login', { mode: 'string' }),
|
||||
createdAt: timestamp('created_at', { mode: 'string' }).defaultNow(),
|
||||
|
||||
+13
-21
@@ -677,10 +677,13 @@ export async function listContainers(all = true, envId?: number | null): Promise
|
||||
}));
|
||||
|
||||
// Extract health status from Status string
|
||||
// Docker formats: "(healthy)", "(unhealthy)", "(health: starting)"
|
||||
let health: string | undefined;
|
||||
const healthMatch = container.Status?.match(/\((healthy|unhealthy|starting)\)/i);
|
||||
const healthMatch = container.Status?.match(/\((healthy|unhealthy|health:\s*starting)\)/i);
|
||||
if (healthMatch) {
|
||||
health = healthMatch[1].toLowerCase();
|
||||
const matched = healthMatch[1].toLowerCase();
|
||||
// Normalize "health: starting" to just "starting"
|
||||
health = matched.includes('starting') ? 'starting' : matched;
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -803,6 +806,7 @@ export interface CreateContainerOptions {
|
||||
labels?: { [key: string]: string };
|
||||
cmd?: string[];
|
||||
restartPolicy?: string;
|
||||
restartMaxRetries?: number;
|
||||
networkMode?: string;
|
||||
networks?: string[];
|
||||
user?: string;
|
||||
@@ -831,7 +835,10 @@ export async function createContainer(options: CreateContainerOptions, envId?: n
|
||||
Labels: options.labels || {},
|
||||
HostConfig: {
|
||||
RestartPolicy: {
|
||||
Name: options.restartPolicy || 'no'
|
||||
Name: options.restartPolicy || 'no',
|
||||
...(options.restartPolicy === 'on-failure' && options.restartMaxRetries !== undefined
|
||||
? { MaximumRetryCount: options.restartMaxRetries }
|
||||
: {})
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -888,9 +895,9 @@ export async function createContainer(options: CreateContainerOptions, envId?: n
|
||||
if (options.networks && options.networks.length > 0) {
|
||||
containerConfig.HostConfig.NetworkMode = options.networks[0];
|
||||
containerConfig.NetworkingConfig = {
|
||||
EndpointsConfig: {
|
||||
[options.networks[0]]: {}
|
||||
}
|
||||
EndpointsConfig: Object.fromEntries(
|
||||
options.networks.map(network => [network, {}])
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -963,21 +970,6 @@ export async function createContainer(options: CreateContainerOptions, envId?: n
|
||||
envId
|
||||
);
|
||||
|
||||
// Connect to additional networks after container creation
|
||||
if (options.networks && options.networks.length > 1) {
|
||||
for (let i = 1; i < options.networks.length; i++) {
|
||||
await dockerFetch(
|
||||
`/networks/${options.networks[i]}/connect`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ Container: result.Id })
|
||||
},
|
||||
envId
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return { id: result.Id, start: () => startContainer(result.Id, envId) };
|
||||
}
|
||||
|
||||
|
||||
+18
-4
@@ -1,5 +1,5 @@
|
||||
import { existsSync, mkdirSync, rmSync, chmodSync } from 'node:fs';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { join, resolve, dirname } from 'node:path';
|
||||
import {
|
||||
getGitRepository,
|
||||
getGitCredential,
|
||||
@@ -134,7 +134,9 @@ export interface SyncResult {
|
||||
success: boolean;
|
||||
commit?: string;
|
||||
composeContent?: string;
|
||||
composeDir?: string; // Directory containing the compose file (for copying all files)
|
||||
envFileVars?: Record<string, string>; // Variables from .env file in repo
|
||||
envFileContent?: string; // Raw .env file content (for Hawser deployments)
|
||||
error?: string;
|
||||
updated?: boolean;
|
||||
}
|
||||
@@ -609,16 +611,21 @@ export async function syncGitStack(stackId: number): Promise<SyncResult> {
|
||||
console.log(`${logPrefix} Compose content:`);
|
||||
console.log(composeContent);
|
||||
|
||||
// Determine the compose directory (for copying all files)
|
||||
const composeDir = dirname(composePath);
|
||||
console.log(`${logPrefix} Compose directory:`, composeDir);
|
||||
|
||||
// Read env file if configured (optional - don't fail if missing)
|
||||
let envFileVars: Record<string, string> | undefined;
|
||||
let envFileContent: string | undefined;
|
||||
if (gitStack.envFilePath) {
|
||||
const envFilePath = join(repoPath, gitStack.envFilePath);
|
||||
console.log(`${logPrefix} Looking for env file at:`, envFilePath);
|
||||
if (existsSync(envFilePath)) {
|
||||
try {
|
||||
console.log(`${logPrefix} Reading env file...`);
|
||||
const envContent = await Bun.file(envFilePath).text();
|
||||
envFileVars = parseEnvFileContent(envContent, gitStack.stackName);
|
||||
envFileContent = await Bun.file(envFilePath).text();
|
||||
envFileVars = parseEnvFileContent(envFileContent, gitStack.stackName);
|
||||
console.log(`${logPrefix} Env file parsed, vars count:`, Object.keys(envFileVars).length);
|
||||
} catch (err) {
|
||||
// Log but don't fail - env file is optional
|
||||
@@ -653,6 +660,7 @@ export async function syncGitStack(stackId: number): Promise<SyncResult> {
|
||||
success: true,
|
||||
commit: currentCommit,
|
||||
composeContent,
|
||||
composeDir,
|
||||
envFileVars,
|
||||
updated
|
||||
};
|
||||
@@ -719,11 +727,13 @@ export async function deployGitStack(stackId: number, options?: { force?: boolea
|
||||
// This ensures containers pick up new env var values even if compose file didn't change
|
||||
// Note: Without this, docker compose only detects compose file changes, not env var changes
|
||||
console.log(`${logPrefix} Calling deployStack...`);
|
||||
console.log(`${logPrefix} Source directory (composeDir):`, syncResult.composeDir);
|
||||
const result = await deployStack({
|
||||
name: gitStack.stackName,
|
||||
compose: syncResult.composeContent!,
|
||||
envId: gitStack.environmentId,
|
||||
envFileVars: syncResult.envFileVars,
|
||||
sourceDir: syncResult.composeDir, // Copy entire directory from git repo
|
||||
forceRecreate
|
||||
});
|
||||
|
||||
@@ -917,6 +927,9 @@ export async function deployGitStackWithProgress(
|
||||
|
||||
const composeContent = await Bun.file(composePath).text();
|
||||
|
||||
// Determine the compose directory (for copying all files)
|
||||
const composeDir = dirname(composePath);
|
||||
|
||||
// Read env file if configured (optional - don't fail if missing)
|
||||
let envFileVars: Record<string, string> | undefined;
|
||||
if (gitStack.envFilePath) {
|
||||
@@ -951,7 +964,8 @@ export async function deployGitStackWithProgress(
|
||||
name: gitStack.stackName,
|
||||
compose: composeContent,
|
||||
envId: gitStack.environmentId,
|
||||
envFileVars
|
||||
envFileVars,
|
||||
sourceDir: composeDir // Copy entire directory from git repo
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
|
||||
@@ -27,6 +27,9 @@ async function sendSmtpNotification(config: SmtpConfig, payload: NotificationPay
|
||||
auth: config.username ? {
|
||||
user: config.username,
|
||||
pass: config.password
|
||||
} : undefined,
|
||||
tls: config.skipTlsVerify ? {
|
||||
rejectUnauthorized: false
|
||||
} : undefined
|
||||
});
|
||||
|
||||
|
||||
+177
-13
@@ -5,11 +5,12 @@
|
||||
* All lifecycle operations use docker compose commands.
|
||||
*/
|
||||
|
||||
import { existsSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
|
||||
import { existsSync, mkdirSync, rmSync, readdirSync, cpSync, statSync } from 'node:fs';
|
||||
import { join, resolve } from 'node:path';
|
||||
import {
|
||||
getEnvironment,
|
||||
getStackEnvVarsAsRecord,
|
||||
setStackEnvVars,
|
||||
getStackSource,
|
||||
upsertStackSource,
|
||||
deleteStackSource,
|
||||
@@ -76,6 +77,7 @@ export interface DeployStackOptions {
|
||||
compose: string;
|
||||
envId?: number | null;
|
||||
envFileVars?: Record<string, string>;
|
||||
sourceDir?: string; // Directory to copy all files from (for git stacks)
|
||||
forceRecreate?: boolean;
|
||||
}
|
||||
|
||||
@@ -156,6 +158,35 @@ async function withStackLock<T>(stackName: string, fn: () => Promise<T>): Promis
|
||||
const COMPOSE_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
|
||||
const COMPOSE_KILL_GRACE_MS = 5000; // 5 seconds grace period before SIGKILL
|
||||
|
||||
/**
|
||||
* Read all files from a directory as a map of relative path -> content.
|
||||
* Used to send files to Hawser for remote deployments.
|
||||
*/
|
||||
async function readDirFilesAsMap(dirPath: string): Promise<Record<string, string>> {
|
||||
const files: Record<string, string> = {};
|
||||
|
||||
async function scanDir(currentPath: string, relativePath: string = ''): Promise<void> {
|
||||
const entries = readdirSync(currentPath, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
const fullPath = join(currentPath, entry.name);
|
||||
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
// Skip .git directory
|
||||
if (entry.name === '.git') continue;
|
||||
await scanDir(fullPath, relPath);
|
||||
} else if (entry.isFile()) {
|
||||
// Read file content
|
||||
const content = await Bun.file(fullPath).text();
|
||||
files[relPath] = content;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await scanDir(dirPath);
|
||||
return files;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// DEBUG UTILITIES
|
||||
// =============================================================================
|
||||
@@ -316,6 +347,7 @@ interface ComposeCommandOptions {
|
||||
envId?: number | null;
|
||||
forceRecreate?: boolean;
|
||||
removeVolumes?: boolean;
|
||||
stackFiles?: Record<string, string>; // All files to send to Hawser
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -338,11 +370,14 @@ async function executeLocalCompose(
|
||||
const composeFile = join(stackDir, 'docker-compose.yml');
|
||||
await Bun.write(composeFile, composeContent);
|
||||
|
||||
// Note: .env file is written when env vars are saved via API
|
||||
// Docker compose automatically reads .env from the stack directory
|
||||
// We only need to pass env vars to process environment for variable substitution
|
||||
// in case the .env file doesn't exist yet (e.g., first deploy)
|
||||
const spawnEnv: Record<string, string> = { ...(process.env as Record<string, string>) };
|
||||
if (dockerHost) {
|
||||
spawnEnv.DOCKER_HOST = dockerHost;
|
||||
}
|
||||
// Add stack-specific environment variables
|
||||
if (envVars) {
|
||||
Object.assign(spawnEnv, envVars);
|
||||
}
|
||||
@@ -479,7 +514,8 @@ async function executeComposeViaHawser(
|
||||
envId: number,
|
||||
envVars?: Record<string, string>,
|
||||
forceRecreate?: boolean,
|
||||
removeVolumes?: boolean
|
||||
removeVolumes?: boolean,
|
||||
stackFiles?: Record<string, string>
|
||||
): Promise<StackOperationResult> {
|
||||
const logPrefix = `[Stack:${stackName}]`;
|
||||
// Import dockerFetch dynamically to avoid circular dependency
|
||||
@@ -497,13 +533,28 @@ async function executeComposeViaHawser(
|
||||
console.log(`${logPrefix} Env vars being sent (masked):`, JSON.stringify(maskSecrets(envVars), null, 2));
|
||||
}
|
||||
console.log(`${logPrefix} Compose content length:`, composeContent.length, 'chars');
|
||||
console.log(`${logPrefix} Stack files count:`, stackFiles ? Object.keys(stackFiles).length : 0);
|
||||
if (stackFiles && Object.keys(stackFiles).length > 0) {
|
||||
console.log(`${logPrefix} Stack files:`, Object.keys(stackFiles).join(', '));
|
||||
}
|
||||
|
||||
try {
|
||||
// Build files map - include .env file if envVars provided
|
||||
const files: Record<string, string> = { ...(stackFiles || {}) };
|
||||
if (envVars && Object.keys(envVars).length > 0) {
|
||||
const envContent = Object.entries(envVars)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join('\n');
|
||||
files['.env'] = envContent;
|
||||
console.log(`${logPrefix} Added .env file to files map with ${Object.keys(envVars).length} variables`);
|
||||
}
|
||||
|
||||
const body = JSON.stringify({
|
||||
operation,
|
||||
projectName: stackName,
|
||||
composeFile: composeContent,
|
||||
envVars: envVars || {},
|
||||
files, // All files including .env
|
||||
forceRecreate: forceRecreate || false,
|
||||
removeVolumes: removeVolumes || false
|
||||
});
|
||||
@@ -567,7 +618,7 @@ async function executeComposeCommand(
|
||||
composeContent: string,
|
||||
envVars?: Record<string, string>
|
||||
): Promise<StackOperationResult> {
|
||||
const { stackName, envId, forceRecreate, removeVolumes } = options;
|
||||
const { stackName, envId, forceRecreate, removeVolumes, stackFiles } = options;
|
||||
|
||||
// Get environment configuration
|
||||
const env = envId ? await getEnvironment(envId) : null;
|
||||
@@ -595,7 +646,8 @@ async function executeComposeCommand(
|
||||
envId!,
|
||||
envVars,
|
||||
forceRecreate,
|
||||
removeVolumes
|
||||
removeVolumes,
|
||||
stackFiles
|
||||
);
|
||||
|
||||
case 'direct': {
|
||||
@@ -808,7 +860,38 @@ async function requireComposeFile(
|
||||
}
|
||||
|
||||
// Get environment variables from database
|
||||
const envVars = await getStackEnvVarsAsRecord(stackName, envId);
|
||||
const dbEnvVars = await getStackEnvVarsAsRecord(stackName, envId);
|
||||
|
||||
// Also read from .env file and merge (file + DB are equal sources)
|
||||
// DB values take precedence for secrets, file values for new/changed vars
|
||||
const stackDir = join(getStacksDir(), stackName);
|
||||
const envFilePath = join(stackDir, '.env');
|
||||
let fileEnvVars: Record<string, string> = {};
|
||||
|
||||
if (existsSync(envFilePath)) {
|
||||
try {
|
||||
const content = await Bun.file(envFilePath).text();
|
||||
for (const line of content.split('\n')) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('#')) continue;
|
||||
const eqIndex = trimmed.indexOf('=');
|
||||
if (eqIndex > 0) {
|
||||
const key = trimmed.substring(0, eqIndex).trim();
|
||||
let value = trimmed.substring(eqIndex + 1);
|
||||
if ((value.startsWith('"') && value.endsWith('"')) ||
|
||||
(value.startsWith("'") && value.endsWith("'"))) {
|
||||
value = value.slice(1, -1);
|
||||
}
|
||||
fileEnvVars[key] = value;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Ignore file read errors
|
||||
}
|
||||
}
|
||||
|
||||
// Merge: file values as base, DB values override (DB is authoritative for managed vars)
|
||||
const envVars = { ...fileEnvVars, ...dbEnvVars };
|
||||
|
||||
return { content: composeResult.content!, envVars };
|
||||
}
|
||||
@@ -1018,7 +1101,7 @@ export async function removeStack(
|
||||
* Uses stack locking to prevent concurrent deployments.
|
||||
*/
|
||||
export async function deployStack(options: DeployStackOptions): Promise<StackOperationResult> {
|
||||
const { name, compose, envId, envFileVars, forceRecreate } = options;
|
||||
const { name, compose, envId, envFileVars, sourceDir, forceRecreate } = options;
|
||||
const logPrefix = `[Stack:${name}]`;
|
||||
|
||||
console.log(`${logPrefix} ========================================`);
|
||||
@@ -1026,6 +1109,7 @@ export async function deployStack(options: DeployStackOptions): Promise<StackOpe
|
||||
console.log(`${logPrefix} ========================================`);
|
||||
console.log(`${logPrefix} Environment ID:`, envId ?? '(none - local)');
|
||||
console.log(`${logPrefix} Force recreate:`, forceRecreate ?? false);
|
||||
console.log(`${logPrefix} Source directory:`, sourceDir ?? '(none)');
|
||||
console.log(`${logPrefix} Env file vars provided:`, envFileVars ? Object.keys(envFileVars).length : 0);
|
||||
if (envFileVars && Object.keys(envFileVars).length > 0) {
|
||||
console.log(`${logPrefix} Env file var keys:`, Object.keys(envFileVars).join(', '));
|
||||
@@ -1043,14 +1127,34 @@ export async function deployStack(options: DeployStackOptions): Promise<StackOpe
|
||||
}
|
||||
|
||||
return withStackLock(name, async () => {
|
||||
// Ensure stack directory exists and write compose file (for local reference)
|
||||
const stacksDir = getStacksDir();
|
||||
const stackDir = join(stacksDir, name);
|
||||
mkdirSync(stackDir, { recursive: true });
|
||||
|
||||
const composeFile = join(stackDir, 'docker-compose.yml');
|
||||
await Bun.write(composeFile, compose);
|
||||
console.log(`${logPrefix} Compose file written to:`, composeFile);
|
||||
// Read all files from source directory if provided (for Hawser deployments)
|
||||
let stackFiles: Record<string, string> | undefined;
|
||||
if (sourceDir && existsSync(sourceDir)) {
|
||||
stackFiles = await readDirFilesAsMap(sourceDir);
|
||||
console.log(`${logPrefix} Read ${Object.keys(stackFiles).length} files from source directory`);
|
||||
console.log(`${logPrefix} Files:`, Object.keys(stackFiles).join(', '));
|
||||
}
|
||||
|
||||
// Handle stack directory setup
|
||||
if (sourceDir && existsSync(sourceDir)) {
|
||||
// Copy entire source directory to stack directory (for git stacks)
|
||||
console.log(`${logPrefix} Copying source directory to stack directory...`);
|
||||
if (existsSync(stackDir)) {
|
||||
rmSync(stackDir, { recursive: true, force: true });
|
||||
}
|
||||
cpSync(sourceDir, stackDir, { recursive: true });
|
||||
console.log(`${logPrefix} Copied ${sourceDir} -> ${stackDir}`);
|
||||
} else {
|
||||
// Traditional behavior: create directory and write compose file only
|
||||
mkdirSync(stackDir, { recursive: true });
|
||||
const composeFile = join(stackDir, 'docker-compose.yml');
|
||||
await Bun.write(composeFile, compose);
|
||||
console.log(`${logPrefix} Compose file written to:`, composeFile);
|
||||
}
|
||||
|
||||
console.log(`${logPrefix} Compose content length:`, compose.length, 'chars');
|
||||
console.log(`${logPrefix} Compose content (full):`);
|
||||
console.log(compose);
|
||||
@@ -1072,7 +1176,7 @@ export async function deployStack(options: DeployStackOptions): Promise<StackOpe
|
||||
}
|
||||
|
||||
console.log(`${logPrefix} Calling executeComposeCommand...`);
|
||||
const result = await executeComposeCommand('up', { stackName: name, envId, forceRecreate }, compose, envVars);
|
||||
const result = await executeComposeCommand('up', { stackName: name, envId, forceRecreate, stackFiles }, compose, envVars);
|
||||
console.log(`${logPrefix} ========================================`);
|
||||
console.log(`${logPrefix} DEPLOY STACK RESULT`);
|
||||
console.log(`${logPrefix} ========================================`);
|
||||
@@ -1099,6 +1203,66 @@ export async function pullStackImages(
|
||||
return executeComposeCommand('pull', { stackName, envId }, content, envVars);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// ENVIRONMENT VARIABLE HELPERS
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Save environment variables for a stack to the database (for secret tracking)
|
||||
*/
|
||||
export async function saveStackEnvVarsToDb(
|
||||
stackName: string,
|
||||
variables: { key: string; value: string; isSecret?: boolean }[],
|
||||
envId?: number | null
|
||||
): Promise<void> {
|
||||
await setStackEnvVars(stackName, envId ?? null, variables);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write environment variables to the .env file on disk (simple key=value format)
|
||||
*
|
||||
* WARNING: This generates a simple key=value file WITHOUT comments or formatting.
|
||||
* ONLY use during initial stack CREATION when no .env file exists.
|
||||
*
|
||||
* For EDITS, use PUT /api/stacks/[name]/env/raw which preserves the raw content
|
||||
* including all comments, formatting, and structure.
|
||||
*/
|
||||
export async function writeStackEnvFile(
|
||||
stackName: string,
|
||||
variables: { key: string; value: string; isSecret?: boolean }[]
|
||||
): Promise<void> {
|
||||
const stacksDir = getStacksDir();
|
||||
const envFilePath = join(stacksDir, stackName, '.env');
|
||||
|
||||
const rawContent = variables
|
||||
.filter(v => v.key?.trim())
|
||||
.map(v => `${v.key.trim()}=${v.value}`)
|
||||
.join('\n') + '\n';
|
||||
|
||||
await Bun.write(envFilePath, rawContent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save environment variables for a stack (both to database and .env file)
|
||||
*
|
||||
* WARNING: Only use during initial stack CREATION - this generates a simple
|
||||
* key=value file that does NOT preserve comments or formatting.
|
||||
*
|
||||
* For EDITS, the StackModal saves to:
|
||||
* - PUT /api/stacks/[name]/env/raw (preserves raw content with comments)
|
||||
* - PUT /api/stacks/[name]/env (updates secret flags in DB only)
|
||||
*/
|
||||
export async function saveStackEnvVars(
|
||||
stackName: string,
|
||||
variables: { key: string; value: string; isSecret?: boolean }[],
|
||||
envId?: number | null
|
||||
): Promise<void> {
|
||||
// Save to database for secret tracking
|
||||
await saveStackEnvVarsToDb(stackName, variables, envId);
|
||||
// Write .env file to disk for Docker Compose
|
||||
await writeStackEnvFile(stackName, variables);
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// RE-EXPORTS FOR BACKWARDS COMPATIBILITY
|
||||
// =============================================================================
|
||||
|
||||
@@ -134,10 +134,16 @@ function processEvent(event: DockerEvent, envId: number) {
|
||||
if (event.Type !== 'container') return;
|
||||
|
||||
// Map Docker action to our action type
|
||||
const action = event.Action.split(':')[0] as ContainerEventAction;
|
||||
// For health_status events, Docker sends "health_status: unhealthy" or "health_status: healthy"
|
||||
// We need to preserve the full string for notifications to distinguish healthy vs unhealthy
|
||||
const rawAction = event.Action;
|
||||
const baseAction = rawAction.split(':')[0] as ContainerEventAction;
|
||||
|
||||
// Skip actions we don't care about
|
||||
if (!CONTAINER_ACTIONS.includes(action)) return;
|
||||
if (!CONTAINER_ACTIONS.includes(baseAction)) return;
|
||||
|
||||
// For notifications, preserve full action for health_status to enable proper mapping
|
||||
const action = rawAction.startsWith('health_status') ? rawAction : baseAction;
|
||||
|
||||
const containerId = event.Actor?.ID;
|
||||
const containerName = event.Actor?.Attributes?.name;
|
||||
@@ -169,14 +175,17 @@ function processEvent(event: DockerEvent, envId: number) {
|
||||
const timestamp = new Date(Math.floor(event.timeNano / 1000000)).toISOString();
|
||||
|
||||
// Prepare notification data
|
||||
const actionLabel = action.charAt(0).toUpperCase() + action.slice(1);
|
||||
// For health_status events, create a cleaner label
|
||||
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 === 'die' || action === 'kill' || action === 'oom' || action.includes('unhealthy')
|
||||
? 'error'
|
||||
: action === 'stop'
|
||||
? 'warning'
|
||||
: action === 'start'
|
||||
: action === 'start' || (action.includes('healthy') && !action.includes('unhealthy'))
|
||||
? 'success'
|
||||
: 'info';
|
||||
|
||||
|
||||
Reference in new issue
Block a user