stack secrets from external providers (1Password, HashiCorp Vault, Infisical and Doppler)
This commit is contained in:
11 files changed
+560
-137
No files matched your search
@@ -0,0 +1,83 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import type { RequestHandler } from './$types';
|
||||
import { getSecretProviderById } from '$lib/server/db';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { getProvider } from '$lib/server/secretproviders';
|
||||
import { UnsupportedOperationError, parseProviderError } from '$lib/server/secretproviders/shared';
|
||||
import { probeBulkKeysCached } from '$lib/server/secretproviders/probe-cache';
|
||||
|
||||
/**
|
||||
* Live probe of a stored provider: given a bulk selector and/or inline op://
|
||||
* references, return which KEY NAMES currently exist in the provider. Only names
|
||||
* are returned - secret values never leave the server. Powers the editor's live
|
||||
* "IN VAULT" marker.
|
||||
*/
|
||||
export const POST: RequestHandler = async ({ params, cookies, request }) => {
|
||||
const auth = await authorize(cookies);
|
||||
if (auth.authEnabled && !(await auth.can('secrets', 'view'))) {
|
||||
return json({ error: 'Permission denied' }, { status: 403 });
|
||||
}
|
||||
|
||||
const id = Number.parseInt(params.id);
|
||||
if (Number.isNaN(id)) {
|
||||
return json({ error: 'Invalid secret provider ID' }, { status: 400 });
|
||||
}
|
||||
|
||||
const row = await getSecretProviderById(id);
|
||||
if (!row) {
|
||||
return json({ error: 'Secret provider not found' }, { status: 404 });
|
||||
}
|
||||
const provider = getProvider(row.type);
|
||||
if (!provider) {
|
||||
return json({ error: `Unknown secret provider type: ${row.type}` }, { status: 400 });
|
||||
}
|
||||
|
||||
let selector: string | undefined;
|
||||
let refs: string[] = [];
|
||||
try {
|
||||
const body = await request.json();
|
||||
if (typeof body?.selector === 'string' && body.selector.trim()) {
|
||||
selector = body.selector.trim();
|
||||
}
|
||||
if (Array.isArray(body?.refs)) {
|
||||
refs = body.refs.filter((r: unknown): r is string => typeof r === 'string' && !!r.trim());
|
||||
}
|
||||
} catch {
|
||||
// empty/invalid body: nothing to probe
|
||||
}
|
||||
|
||||
let bulkKeys: string[] = [];
|
||||
let resolvedRefs: string[] = [];
|
||||
|
||||
// A provider missing a mode throws UnsupportedOperationError; that is not a
|
||||
// failure - it just means that mode contributes no keys. Any other throw
|
||||
// (network, bad token, bad path) is a real probe failure.
|
||||
if (selector && provider.supportsBulk) {
|
||||
try {
|
||||
bulkKeys = await probeBulkKeysCached(id, provider, row.config, selector);
|
||||
} catch (e) {
|
||||
if (!(e instanceof UnsupportedOperationError)) {
|
||||
return json({ ok: false, error: shortError(e) }, { status: 200 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (refs.length && provider.supportsReferences) {
|
||||
try {
|
||||
const resolved = await provider.resolveSecretReferences(row.config, refs);
|
||||
resolvedRefs = [...resolved.keys()];
|
||||
} catch (e) {
|
||||
if (!(e instanceof UnsupportedOperationError)) {
|
||||
return json({ ok: false, error: shortError(e) }, { status: 200 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return json({ ok: true, bulkKeys, resolvedRefs });
|
||||
};
|
||||
|
||||
/** A short, non-reflecting error message for the probe-failed UI line. */
|
||||
function shortError(e: unknown): string {
|
||||
const raw = e instanceof Error ? e.message : String(e);
|
||||
return parseProviderError(raw) ?? raw.slice(0, 200);
|
||||
}
|
||||
+11
-2
@@ -1,5 +1,5 @@
|
||||
import { json } from '@sveltejs/kit';
|
||||
import { getStackEnvVars, setStackEnvVars, getStackSource } from '$lib/server/db';
|
||||
import { getStackEnvVars, setStackEnvVars, getStackSource, getStackInjectedSecretKeys, getSecretProviderById } from '$lib/server/db';
|
||||
import { findStackDir } from '$lib/server/stacks';
|
||||
import { authorize } from '$lib/server/authorize';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
@@ -107,7 +107,16 @@ export const GET: RequestHandler = async ({ params, url, cookies }) => {
|
||||
}
|
||||
}
|
||||
|
||||
return json({ variables });
|
||||
// Provider-injected key NAMES from the last deploy (no values) + the bound
|
||||
// provider's type/name, so the UI can show "these were loaded from <provider>".
|
||||
const injectedSecretKeys = [...await getStackInjectedSecretKeys(stackName, envIdNum ?? undefined)];
|
||||
let secretProvider: { type: string; name: string } | null = null;
|
||||
if (source?.secretProviderId) {
|
||||
const p = await getSecretProviderById(source.secretProviderId);
|
||||
if (p) secretProvider = { type: p.type, name: p.name };
|
||||
}
|
||||
|
||||
return json({ variables, injectedSecretKeys, secretProvider });
|
||||
} catch (error) {
|
||||
console.error('Error getting stack env vars:', error);
|
||||
return json({ error: 'Failed to get environment variables' }, { status: 500 });
|
||||
|
||||
@@ -30,35 +30,58 @@
|
||||
// secretproviders/shared.ts. Non-required fields are optional overrides.
|
||||
export const PROVIDER_FIELDS: Record<string, ProviderField[]> = {
|
||||
'op-service-account': [
|
||||
{ key: 'token', label: 'Service account token', type: 'password', required: true, placeholder: 'ops_eyJ...' },
|
||||
{ key: 'token', label: 'Service account token', type: 'password', required: true, placeholder: 'ops_eyJ...', hint: 'A 1Password service account token (starts with ops_).' },
|
||||
],
|
||||
'op-connect': [
|
||||
{ key: 'host', label: 'Connect host URL', type: 'text', required: true, placeholder: 'https://connect.example.com' },
|
||||
{ key: 'token', label: 'Connect token', type: 'password', required: true, placeholder: 'eyJ...' },
|
||||
{ key: 'host', label: 'Connect host URL', type: 'text', required: true, placeholder: 'https://connect.example.com', hint: 'URL of your 1Password Connect server.' },
|
||||
{ key: 'token', label: 'Connect token', type: 'password', required: true, placeholder: 'eyJ...', hint: 'A Connect access token with read access to the vault.' },
|
||||
],
|
||||
infisical: [
|
||||
{ key: 'host', label: 'API host', type: 'text', required: true, placeholder: 'https://app.infisical.com' },
|
||||
{ key: 'token', label: 'Access token', type: 'password', required: true, placeholder: 'st...' },
|
||||
{ key: 'projectId', label: 'Project ID', type: 'text', required: true, placeholder: 'workspace / project id' },
|
||||
{ key: 'environment', label: 'Environment', type: 'text', required: true, placeholder: 'prod' },
|
||||
{ key: 'path', label: 'Secret path', type: 'text', required: false, placeholder: '/' },
|
||||
{ key: 'host', label: 'API host', type: 'text', required: true, placeholder: 'https://app.infisical.com', hint: 'Infisical Cloud or your self-hosted URL.' },
|
||||
{ key: 'token', label: 'Access token', type: 'password', required: true, placeholder: 'st...', hint: 'A service token or machine-identity access token.' },
|
||||
{ key: 'projectId', label: 'Project ID', type: 'text', required: true, placeholder: 'workspace / project id', hint: 'The workspace/project the secrets live in.' },
|
||||
{ key: 'environment', label: 'Environment', type: 'text', required: true, placeholder: 'prod', hint: 'Environment slug, e.g. prod / staging.' },
|
||||
{ key: 'path', label: 'Secret path', type: 'text', required: false, placeholder: '/', hint: 'Folder path within the project. Defaults to /.' },
|
||||
],
|
||||
vault: [
|
||||
{ key: 'address', label: 'Vault address', type: 'text', required: true, placeholder: 'https://vault.example.com' },
|
||||
{ key: 'token', label: 'Vault token', type: 'password', required: true, placeholder: 'hvs...' },
|
||||
{ key: 'namespace', label: 'Namespace', type: 'text', required: false, placeholder: 'admin (Enterprise / HCP)' },
|
||||
{ key: 'mount', label: 'KV mount', type: 'text', required: false, placeholder: 'secret' },
|
||||
{ key: 'address', label: 'Vault address', type: 'text', required: true, placeholder: 'https://vault.example.com', hint: 'Base URL of your Vault server.' },
|
||||
{ key: 'token', label: 'Vault token', type: 'password', required: true, placeholder: 'hvs...', hint: 'A token with read access to the KV path.' },
|
||||
{ key: 'namespace', label: 'Namespace', type: 'text', required: false, placeholder: 'admin (Enterprise / HCP)', hint: 'Vault Enterprise / HCP only.' },
|
||||
{ key: 'mount', label: 'KV mount', type: 'text', required: false, placeholder: 'secret', hint: 'KV v2 mount path. Defaults to "secret".' },
|
||||
],
|
||||
doppler: [
|
||||
{ key: 'token', label: 'Token', type: 'password', required: true, placeholder: 'dp.st.... or dp.pt....', hint: 'A service token (dp.st.) already targets one config. A personal token (dp.pt.) also needs the project and config below.' },
|
||||
{ key: 'project', label: 'Project', type: 'text', required: false, placeholder: 'only for a personal token (dp.pt.)' },
|
||||
{ key: 'config', label: 'Config', type: 'text', required: false, placeholder: 'e.g. prd' },
|
||||
{ key: 'project', label: 'Project', type: 'text', required: false, placeholder: 'only for a personal token (dp.pt.)', hint: 'Doppler project slug. Only needed with a personal token.' },
|
||||
{ key: 'config', label: 'Config', type: 'text', required: false, placeholder: 'e.g. prd', hint: 'Config within the project. Only needed with a personal token.' },
|
||||
],
|
||||
};
|
||||
|
||||
export function providerTypeLabel(type: string): string {
|
||||
return PROVIDER_TYPES.find((t) => t.value === type)?.label ?? type;
|
||||
}
|
||||
|
||||
// Per-stack bulk-selector field metadata (UI-only, like PROVIDER_FIELDS above).
|
||||
// A provider type with no entry shows no selector field: doppler ignores the
|
||||
// selector, connect has no bulk pull. The field's value is written to the stack
|
||||
// env as DOCKHAND_SECRET_SELECTOR (consumed by resolveProviderEnvVars).
|
||||
export type BulkSelectorField = { label: string; placeholder?: string; hint?: string };
|
||||
export const BULK_SELECTOR_FIELDS: Record<string, BulkSelectorField> = {
|
||||
'op-service-account': {
|
||||
label: 'Environment',
|
||||
placeholder: '1Password Environment id',
|
||||
hint: 'Bulk-load every secret from this 1Password Environment. Leave blank to inject only inline op:// references.'
|
||||
},
|
||||
'vault': {
|
||||
label: 'KV v2 path',
|
||||
placeholder: 'path/to/secret',
|
||||
hint: 'Bulk-load every key at this KV v2 path (under the configured mount).'
|
||||
},
|
||||
'infisical': {
|
||||
label: 'Secret path',
|
||||
placeholder: '/',
|
||||
hint: 'Bulk-load every secret at this path (project and environment come from the provider config).'
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<script lang='ts'>
|
||||
@@ -102,6 +125,11 @@
|
||||
let testOkTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const fields = $derived(PROVIDER_FIELDS[formType] ?? []);
|
||||
// Providers whose config fields read better stacked one per row rather than in the
|
||||
// 2-column grid (per-field hints, or fields long enough to want full width).
|
||||
const stackConfigFields = $derived(
|
||||
formType === 'op-connect' || formType === 'doppler'
|
||||
);
|
||||
|
||||
function resetConfig() {
|
||||
formConfig = {};
|
||||
@@ -299,7 +327,7 @@
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Dialog.Content class="sm:max-w-lg">
|
||||
<Dialog.Content class="sm:max-w-2xl">
|
||||
<Dialog.Header>
|
||||
<Dialog.Title class="flex items-center gap-2">
|
||||
<KeyRound class="w-5 h-5 text-muted-foreground" />
|
||||
@@ -320,7 +348,7 @@
|
||||
placeholder="Production secrets"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-2 sm:w-[calc(50%-0.5rem)]">
|
||||
<div class="space-y-2">
|
||||
<FieldLabel label="Provider" forId="provider-type" required showOptional={false} />
|
||||
<Select.Root
|
||||
type="single"
|
||||
@@ -328,10 +356,12 @@
|
||||
onValueChange={onTypeChange}
|
||||
disabled={isEditing}
|
||||
>
|
||||
<Select.Trigger id="provider-type" class="flex w-full items-center gap-2">
|
||||
<Select.Trigger id="provider-type" class="w-full justify-between gap-2">
|
||||
{@const TriggerIcon = getProviderIcon(formType)}
|
||||
<TriggerIcon class="w-4 h-4 shrink-0 text-muted-foreground" />
|
||||
{providerTypeLabel(formType)}
|
||||
<span class="flex items-center gap-2 min-w-0">
|
||||
<TriggerIcon class="w-4 h-4 shrink-0 text-muted-foreground" />
|
||||
<span class="truncate">{providerTypeLabel(formType)}</span>
|
||||
</span>
|
||||
</Select.Trigger>
|
||||
<Select.Content>
|
||||
{#each PROVIDER_TYPES as t (t.value)}
|
||||
@@ -346,12 +376,12 @@
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
</div>
|
||||
<!-- Provider config fields in a 2-column grid. min-height fits the tallest
|
||||
provider (5 fields = 3 rows) so the modal keeps a fixed height and does
|
||||
not jump when switching providers. -->
|
||||
<div class="grid grid-cols-2 gap-x-4 gap-y-3" style="min-height: 13.5rem;">
|
||||
<!-- Provider config fields: a 2-column grid, or one per row for providers whose
|
||||
fields read better stacked (Vault, Connect, Doppler). min-height +
|
||||
content-start keep the dialog a stable height while laying rows top-aligned. -->
|
||||
<div class="grid {stackConfigFields ? 'grid-cols-1' : 'grid-cols-2'} gap-x-4 gap-y-3 content-start" style="min-height: 21rem;">
|
||||
{#each fields as field (field.key)}
|
||||
<div class="space-y-2">
|
||||
<div class="space-y-1.5 self-start {fields.length === 1 ? 'col-span-full' : ''}">
|
||||
<FieldLabel label={field.label} forId={`provider-${field.key}`} required={field.required} />
|
||||
<Input
|
||||
id={`provider-${field.key}`}
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
import { copyToClipboard } from '$lib/utils/clipboard';
|
||||
import CronEditor from '$lib/components/cron-editor.svelte';
|
||||
import StackEnvVarsPanel from '$lib/components/StackEnvVarsPanel.svelte';
|
||||
import SecretProviderPicker from '$lib/components/SecretProviderPicker.svelte';
|
||||
import { type EnvVar, type ValidationResult } from '$lib/components/StackEnvVarsEditor.svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { focusFirstInput } from '$lib/utils';
|
||||
@@ -155,9 +156,10 @@
|
||||
let copiedWebhookSecret = $state<'ok' | 'error' | null>(null);
|
||||
|
||||
// Secret providers
|
||||
type SecretProviderOption = { id: number; name: string };
|
||||
type SecretProviderOption = { id: number; name: string; type: string };
|
||||
let secretProviders = $state<SecretProviderOption[]>([]);
|
||||
let formSecretProviderId = $state<number | null>(null);
|
||||
let injectedSecretKeys = $state<string[]>([]);
|
||||
|
||||
// Environment variables state
|
||||
let formEnvFilePath = $state<string | null>(null);
|
||||
@@ -219,7 +221,7 @@
|
||||
const response = await fetch('/api/secret-providers');
|
||||
if (!response.ok) return;
|
||||
const data = await response.json();
|
||||
secretProviders = (data ?? []).map((p: any) => ({ id: p.id, name: p.name }));
|
||||
secretProviders = (data ?? []).map((p: any) => ({ id: p.id, name: p.name, type: p.type }));
|
||||
} catch (e) {
|
||||
console.warn('Failed to load secret providers:', e);
|
||||
}
|
||||
@@ -332,6 +334,7 @@
|
||||
);
|
||||
// Set envVars - the panel's $effect will auto-sync rawContent for text view
|
||||
envVars = loadedVars;
|
||||
injectedSecretKeys = data.injectedSecretKeys ?? [];
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load env var overrides:', e);
|
||||
@@ -1188,46 +1191,16 @@
|
||||
|
||||
<!-- Right column: Environment Variables -->
|
||||
<div class="flex-1 min-w-0 flex flex-col overflow-hidden bg-zinc-50 dark:bg-zinc-800/50">
|
||||
<!-- Secret provider selector - hidden when no external provider is configured
|
||||
(still shown if this stack already has one bound, so it can be cleared). -->
|
||||
{#if secretProviders.length > 0 || formSecretProviderId !== null}
|
||||
<div class="px-3 py-2 border-b border-zinc-200 dark:border-zinc-700 bg-zinc-100/60 dark:bg-zinc-800/60 flex items-center gap-2 text-xs">
|
||||
<Label for="secret-provider-select-git" class="text-xs text-muted-foreground shrink-0">Secret provider</Label>
|
||||
<Select.Root
|
||||
type="single"
|
||||
value={formSecretProviderId !== null ? String(formSecretProviderId) : ''}
|
||||
onValueChange={(v) => { formSecretProviderId = v ? parseInt(v) : null; }}
|
||||
>
|
||||
<Select.Trigger id="secret-provider-select-git" class="h-7 text-xs">
|
||||
{#if formSecretProviderId !== null}
|
||||
{secretProviders.find((p) => p.id === formSecretProviderId)?.name ?? 'Unknown provider'}
|
||||
{:else}
|
||||
<span class="text-muted-foreground">None — disabled</span>
|
||||
{/if}
|
||||
</Select.Trigger>
|
||||
<Select.Content>
|
||||
<Select.Item value="" label="None">
|
||||
<span class="text-muted-foreground">None — disabled</span>
|
||||
</Select.Item>
|
||||
{#each secretProviders as provider (provider.id)}
|
||||
<Select.Item value={String(provider.id)} label={provider.name}>
|
||||
{provider.name}
|
||||
</Select.Item>
|
||||
{/each}
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
<Tooltip.Root>
|
||||
<Tooltip.Trigger>
|
||||
<HelpCircle class="w-3.5 h-3.5 text-muted-foreground shrink-0" />
|
||||
</Tooltip.Trigger>
|
||||
<Tooltip.Content class="max-w-xs text-xs">
|
||||
Inline references (e.g. <code>op://</code> for 1Password) are still resolved. For bulk pull, set <code>OP_ENVIRONMENT_ID</code> (1Password Environment) or the generic <code>DOCKHAND_SECRET_SELECTOR</code> in env vars; the provider's secrets are loaded and injected.
|
||||
</Tooltip.Content>
|
||||
</Tooltip.Root>
|
||||
</div>
|
||||
{/if}
|
||||
<SecretProviderPicker
|
||||
bind:secretProviderId={formSecretProviderId}
|
||||
bind:envVars
|
||||
providers={secretProviders}
|
||||
/>
|
||||
<StackEnvVarsPanel
|
||||
bind:variables={envVars}
|
||||
injectedSecretKeys={gitStack !== null ? injectedSecretKeys : []}
|
||||
providerType={secretProviders.find((p) => p.id === formSecretProviderId)?.type ?? null}
|
||||
providerName={secretProviders.find((p) => p.id === formSecretProviderId)?.name ?? null}
|
||||
placeholder={{ key: 'MY_VAR', value: 'value' }}
|
||||
infoText="Override variables from your repository env files. Non-secrets are saved to <code class='bg-muted px-1 rounded'>.env.dockhand</code> in the stack directory. Secrets are stored in the database and injected via shell environment at deploy time.<br/><br/>Variables are available for <strong>compose file interpolation</strong> using <code class='bg-muted px-1 rounded'>${'{VAR_NAME}'}</code> syntax. They are not automatically injected into containers — use <code class='bg-muted px-1 rounded'>environment:</code> or reference <code class='bg-muted px-1 rounded'>.env.dockhand</code> in <code class='bg-muted px-1 rounded'>env_file:</code> to pass them through."
|
||||
existingSecretKeys={gitStack !== null ? existingSecretKeys : new Set()}
|
||||
|
||||
@@ -7,7 +7,10 @@
|
||||
import CodeEditor, { type VariableMarker } from '$lib/components/CodeEditor.svelte';
|
||||
import StackEnvVarsPanel from '$lib/components/StackEnvVarsPanel.svelte';
|
||||
import { type EnvVar, type ValidationResult } from '$lib/components/StackEnvVarsEditor.svelte';
|
||||
import { Layers, Save, Play, Code, GitGraph, GitBranch, GitCommitHorizontal, Github, Loader2, AlertCircle, X, Sun, Moon, TriangleAlert, GripVertical, FolderOpen, Copy, Check, XCircle, MapPin, ArrowRight, ArrowDown, Info, Box, FolderSync, HelpCircle, Archive } from 'lucide-svelte';
|
||||
import SecretProviderPicker from '$lib/components/SecretProviderPicker.svelte';
|
||||
import { SELECTOR_VARS } from '$lib/utils/bulk-selector';
|
||||
import { classifyMarker, resolvedRefVarNames } from '$lib/utils/invault-markers';
|
||||
import { Layers, Save, Play, Code, GitGraph, GitBranch, GitCommitHorizontal, Github, Loader2, AlertCircle, X, Sun, Moon, TriangleAlert, GripVertical, FolderOpen, Copy, Check, XCircle, MapPin, ArrowRight, ArrowDown, Info, Box, FolderSync, Archive } from 'lucide-svelte';
|
||||
import BackupPanel from '../containers/BackupPanel.svelte';
|
||||
import { volumesForStack, type VolumeInfo } from '$lib/utils/mounts';
|
||||
import { fetchBackupExecutions } from '$lib/utils/backup';
|
||||
@@ -15,7 +18,6 @@
|
||||
import FilesystemBrowser from './FilesystemBrowser.svelte';
|
||||
import PathBarItem from './PathBarItem.svelte';
|
||||
import * as Tooltip from '$lib/components/ui/tooltip';
|
||||
import * as Select from '$lib/components/ui/select';
|
||||
import { Badge } from '$lib/components/ui/badge';
|
||||
import { currentEnvironment, appendEnvParam } from '$lib/stores/environment';
|
||||
import { appSettings } from '$lib/stores/settings';
|
||||
@@ -71,9 +73,24 @@
|
||||
let backupPanelRef = $state<BackupPanel | undefined>(undefined);
|
||||
|
||||
// Secret providers
|
||||
type SecretProviderOption = { id: number; name: string };
|
||||
type SecretProviderOption = { id: number; name: string; type: string };
|
||||
let secretProviders = $state<SecretProviderOption[]>([]);
|
||||
let formSecretProviderId = $state<number | null>(null);
|
||||
// Provider-injected key NAMES from the last deploy (banner)
|
||||
let injectedSecretKeys = $state<string[]>([]);
|
||||
// Provider type/name for the injected-secrets banner in the env panel.
|
||||
const selectedProviderType = $derived(
|
||||
secretProviders.find((p) => p.id === formSecretProviderId)?.type ?? null
|
||||
);
|
||||
const selectedProviderName = $derived(
|
||||
secretProviders.find((p) => p.id === formSecretProviderId)?.name ?? null
|
||||
);
|
||||
// Live probe of the bound provider: key NAMES currently present (bulk + resolved
|
||||
// inline refs). Drives the editor's green IN VAULT marker. Empty when no provider
|
||||
// is bound or the probe failed; probeError holds the reason on failure.
|
||||
let providerKeySet = $state<Set<string>>(new Set());
|
||||
let probeError = $state<string | null>(null);
|
||||
let probeSeq = 0;
|
||||
|
||||
// Environment variables state
|
||||
let envVars = $state<EnvVar[]>([]);
|
||||
@@ -81,11 +98,9 @@
|
||||
let envValidation = $state<ValidationResult | null>(null);
|
||||
let validating = $state(false);
|
||||
|
||||
// The bulk-pull selector vars (OP_ENVIRONMENT_ID for 1Password, the generic
|
||||
// DOCKHAND_SECRET_SELECTOR for other providers) are consumed by the secret
|
||||
// provider, not the compose file, so they only count as "used" when a provider
|
||||
// is bound to the stack.
|
||||
const SELECTOR_VARS = ['OP_ENVIRONMENT_ID', 'DOCKHAND_SECRET_SELECTOR'];
|
||||
// SELECTOR_VARS (OP_ENVIRONMENT_ID / DOCKHAND_SECRET_SELECTOR) are consumed by the
|
||||
// secret provider, not the compose file, so they only count as "used" when a
|
||||
// provider is bound to the stack.
|
||||
const effectiveValidation = $derived.by<ValidationResult | null>(() => {
|
||||
if (!envValidation || formSecretProviderId === null) return envValidation;
|
||||
if (!envValidation.unused.some((v) => SELECTOR_VARS.includes(v))) return envValidation;
|
||||
@@ -619,12 +634,14 @@
|
||||
|
||||
const markers: VariableMarker[] = [];
|
||||
|
||||
// Add missing required variables
|
||||
// Add missing required variables - but a var the bound provider currently has
|
||||
// (live probe) is 'invault' (green), not 'missing' (red). A failed probe forces
|
||||
// MISSING so we never show a false green.
|
||||
for (const name of envValidation.missing) {
|
||||
const env = envVarMap.get(name);
|
||||
markers.push({
|
||||
name,
|
||||
type: 'missing',
|
||||
type: classifyMarker(name, true, providerKeySet, probeError !== null),
|
||||
value: env?.value,
|
||||
isSecret: env?.isSecret
|
||||
});
|
||||
@@ -664,14 +681,80 @@
|
||||
debouncedValidate();
|
||||
}
|
||||
|
||||
// Debounced validation to avoid too many API calls while typing
|
||||
// Debounced validation to avoid too many API calls while typing. The live
|
||||
// provider probe rides the same cadence so it doesn't hammer the provider.
|
||||
function debouncedValidate() {
|
||||
if (validateTimer) clearTimeout(validateTimer);
|
||||
validateTimer = setTimeout(() => {
|
||||
validateEnvVars();
|
||||
runProbe();
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
// op://... inline references in the current env vars, mapped var -> ref, so a
|
||||
// resolved ref (the provider returns ref STRINGS) maps back to its var name.
|
||||
function inlineRefPairs(): { varName: string; ref: string }[] {
|
||||
const pairs: { varName: string; ref: string }[] = [];
|
||||
for (const v of envVars) {
|
||||
const key = v.key.trim();
|
||||
const val = (v.value ?? '').trim();
|
||||
if (key && val.startsWith('op://')) pairs.push({ varName: key, ref: val });
|
||||
}
|
||||
return pairs;
|
||||
}
|
||||
|
||||
// Live-probe the bound provider for which required keys exist RIGHT NOW. Only
|
||||
// key NAMES cross the wire. Guardrails: a provider must be selected; on any
|
||||
// failure the key set is emptied and probeError is set (-> everything MISSING,
|
||||
// never a false green). Guarded by probeSeq to drop stale responses.
|
||||
async function runProbe() {
|
||||
if (formSecretProviderId === null) {
|
||||
providerKeySet = new Set();
|
||||
probeError = null;
|
||||
return;
|
||||
}
|
||||
const selector = (() => {
|
||||
for (const name of SELECTOR_VARS) {
|
||||
const hit = envVars.find((v) => v.key.trim() === name);
|
||||
if (hit && hit.value.trim()) return hit.value.trim();
|
||||
}
|
||||
return undefined;
|
||||
})();
|
||||
const refPairs = inlineRefPairs();
|
||||
if (!selector && refPairs.length === 0) {
|
||||
providerKeySet = new Set();
|
||||
probeError = null;
|
||||
updateEditorMarkers();
|
||||
return;
|
||||
}
|
||||
const seq = ++probeSeq;
|
||||
try {
|
||||
const response = await fetch(`/api/secret-providers/${formSecretProviderId}/probe`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ selector, refs: refPairs.map((p) => p.ref) })
|
||||
});
|
||||
if (seq !== probeSeq) return; // a newer probe superseded this one
|
||||
const data = await response.json();
|
||||
if (!response.ok || !data.ok) {
|
||||
providerKeySet = new Set();
|
||||
probeError = data.error || `Provider check failed (${response.status})`;
|
||||
} else {
|
||||
const names = [
|
||||
...(data.bulkKeys ?? []),
|
||||
...resolvedRefVarNames(refPairs, data.resolvedRefs ?? [])
|
||||
];
|
||||
providerKeySet = new Set(names);
|
||||
probeError = null;
|
||||
}
|
||||
} catch (e) {
|
||||
if (seq !== probeSeq) return;
|
||||
providerKeySet = new Set();
|
||||
probeError = e instanceof Error ? e.message : 'Provider check failed';
|
||||
}
|
||||
updateEditorMarkers();
|
||||
}
|
||||
|
||||
// Explicitly push markers to the editor (immediate=true since this is called after validation)
|
||||
function updateEditorMarkers() {
|
||||
if (!codeEditorRef) return;
|
||||
@@ -722,7 +805,7 @@
|
||||
const response = await fetch('/api/secret-providers');
|
||||
if (!response.ok) return;
|
||||
const data = await response.json();
|
||||
secretProviders = (data ?? []).map((p: any) => ({ id: p.id, name: p.name }));
|
||||
secretProviders = (data ?? []).map((p: any) => ({ id: p.id, name: p.name, type: p.type }));
|
||||
} catch (e) {
|
||||
console.warn('Failed to load secret providers:', e);
|
||||
}
|
||||
@@ -877,6 +960,8 @@
|
||||
existingSecretKeys = new Set(
|
||||
loadedVars.filter(v => v.isSecret && v.key.trim()).map(v => v.key.trim())
|
||||
);
|
||||
// Provider-injected key names from the last deploy (banner)
|
||||
injectedSecretKeys = envData.injectedSecretKeys ?? [];
|
||||
}
|
||||
|
||||
// Process raw .env file content
|
||||
@@ -1319,6 +1404,7 @@
|
||||
loadComposeFile().then(() => {
|
||||
// Auto-validate after loading
|
||||
validateEnvVars();
|
||||
runProbe();
|
||||
});
|
||||
} else if (mode === 'create') {
|
||||
// Set default compose content for create mode (library templates override default)
|
||||
@@ -1330,6 +1416,7 @@
|
||||
loading = false;
|
||||
// Auto-validate default compose
|
||||
validateEnvVars();
|
||||
runProbe();
|
||||
}
|
||||
} else if (!open) {
|
||||
hasInitialized = false; // Reset when modal closes
|
||||
@@ -1345,6 +1432,7 @@
|
||||
// Debounce to avoid too many API calls while typing
|
||||
const timeout = setTimeout(() => {
|
||||
validateEnvVars();
|
||||
runProbe();
|
||||
}, 800);
|
||||
|
||||
return () => clearTimeout(timeout);
|
||||
@@ -1758,55 +1846,22 @@
|
||||
</div>
|
||||
<!-- Environment variables panel -->
|
||||
<div class="flex-1 min-w-0 flex flex-col overflow-hidden bg-zinc-50 dark:bg-zinc-800/50">
|
||||
<!-- Secret provider selector - hidden when no external provider is configured
|
||||
(still shown if this stack already has one bound, so it can be cleared). -->
|
||||
{#if secretProviders.length > 0 || formSecretProviderId !== null}
|
||||
<div class="px-3 py-2 border-b border-zinc-200 dark:border-zinc-700 bg-zinc-100/60 dark:bg-zinc-800/60 flex items-center gap-2 text-xs">
|
||||
<Label for="secret-provider-select" class="text-xs text-muted-foreground shrink-0">Secret provider</Label>
|
||||
<Select.Root
|
||||
type="single"
|
||||
value={formSecretProviderId !== null ? String(formSecretProviderId) : ''}
|
||||
onValueChange={(v) => {
|
||||
formSecretProviderId = v ? parseInt(v) : null;
|
||||
markDirty();
|
||||
}}
|
||||
>
|
||||
<Select.Trigger id="secret-provider-select" class="h-7 text-xs">
|
||||
{#if formSecretProviderId !== null}
|
||||
{secretProviders.find((p) => p.id === formSecretProviderId)?.name ?? 'Unknown provider'}
|
||||
{:else}
|
||||
<span class="text-muted-foreground">None — disabled</span>
|
||||
{/if}
|
||||
</Select.Trigger>
|
||||
<Select.Content>
|
||||
<Select.Item value="" label="None">
|
||||
<span class="text-muted-foreground">None — disabled</span>
|
||||
</Select.Item>
|
||||
{#each secretProviders as provider (provider.id)}
|
||||
<Select.Item value={String(provider.id)} label={provider.name}>
|
||||
{provider.name}
|
||||
</Select.Item>
|
||||
{/each}
|
||||
</Select.Content>
|
||||
</Select.Root>
|
||||
<Tooltip.Provider delayDuration={150}>
|
||||
<Tooltip.Root>
|
||||
<Tooltip.Trigger>
|
||||
<HelpCircle class="w-3.5 h-3.5 text-muted-foreground shrink-0" />
|
||||
</Tooltip.Trigger>
|
||||
<Tooltip.Content class="max-w-xs text-xs">
|
||||
Inline references (e.g. <code>op://</code> for 1Password) are still resolved. For bulk pull, set <code>OP_ENVIRONMENT_ID</code> (1Password Environment) or the generic <code>DOCKHAND_SECRET_SELECTOR</code> in env vars; the provider's secrets are loaded and injected.
|
||||
</Tooltip.Content>
|
||||
</Tooltip.Root>
|
||||
</Tooltip.Provider>
|
||||
</div>
|
||||
{/if}
|
||||
<SecretProviderPicker
|
||||
bind:secretProviderId={formSecretProviderId}
|
||||
bind:envVars
|
||||
providers={secretProviders}
|
||||
onchange={() => { markDirty(); debouncedValidate(); }}
|
||||
/>
|
||||
<StackEnvVarsPanel
|
||||
bind:this={envVarsPanelRef}
|
||||
bind:variables={envVars}
|
||||
bind:rawContent={rawEnvContent}
|
||||
validation={effectiveValidation}
|
||||
existingSecretKeys={mode === 'edit' ? existingSecretKeys : new Set()}
|
||||
injectedSecretKeys={mode === 'edit' ? injectedSecretKeys : []}
|
||||
providerType={selectedProviderType}
|
||||
providerName={selectedProviderName}
|
||||
{probeError}
|
||||
{readonly}
|
||||
onchange={() => { markDirty(); debouncedValidate(); }}
|
||||
theme={editorTheme}
|
||||
|
||||
Reference in new issue
Block a user