Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

20.5 KB
Raw Blame
import { createEffect, createMemo, createSignal, onCleanup, onMount } from 'solid-js';
import { useLocation, useNavigate } from '@solidjs/router';
import { MonitoringAPI } from '@/api/monitoring';
import { NodesAPI } from '@/api/nodes';
import { SecurityAPI, type APITokenRecord } from '@/api/security';
import { notificationStore } from '@/stores/notifications';
import { showTokenReveal } from '@/stores/tokenReveal';
import type { AgentLookupResponse, ConnectedInfrastructureItem } from '@/types/api';
import type { SecurityStatus } from '@/types/config';
import { copyToClipboard } from '@/utils/clipboard';
import { getPulseBaseUrl } from '@/utils/url';
import { logger } from '@/utils/logger';
import { STORAGE_KEYS } from '@/utils/localStorage';
import {
  buildInfrastructureOnboardingPath,
  buildInfrastructureWorkspacePath,
  deriveAddStepFromLocation,
  type InfrastructurePanelStep,
} from './infrastructureWorkspaceModel';
import {
  buildUnixAgentInstallCommand,
  buildWindowsAgentInstallCommand,
  resolveInstallerBaseUrl,
} from '@/utils/agentInstallCommand';
import { getUnifiedAgentClipboardCopyErrorMessage } from '@/utils/unifiedAgentInventoryPresentation';
import {
  buildCommandsByPlatform,
  buildDefaultTokenName,
  getPowerShellInstallProfileEnvFromFlags,
  INSTALL_PROFILE_OPTIONS,
  TOKEN_PLACEHOLDER,
  type AgentPlatform,
  type InstallProfile,
  type SetupHandoffState,
} from './infrastructureOperationsModel';

export interface InfrastructureInstallStateOptions {
  embedded?: boolean;
}

const FIRST_HOST_AUTODETECT_POLL_MS = 3000;
const SETUP_HANDOFF_INSTALL_STEPS = new Set<InfrastructurePanelStep>([
  'agent',
  'linux-host',
  'unraid',
  'docker',
  'kubernetes',
]);
const INSTALL_TOKEN_REVEAL_NOTE =
  'For Unix installation, run the copied command first, then paste this token only at the silent “Pulse agent token” prompt. The no-terminal command reads the private token file named beside it instead. Never insert the token into a Unix command. For Windows or container configuration, keep copied credentials private.';

const isActiveInfrastructureItem = (item: ConnectedInfrastructureItem) => item.status === 'active';

const pickMostRecentInfrastructureItem = (
  items: ConnectedInfrastructureItem[],
): ConnectedInfrastructureItem | null => {
  if (items.length === 0) {
    return null;
  }

  return [...items].sort((left, right) => (right.lastSeen || 0) - (left.lastSeen || 0))[0];
};

const toLookupResponseFromInfrastructureItem = (
  item: ConnectedInfrastructureItem,
): AgentLookupResponse => ({
  success: true,
  agent: {
    id: item.scopeAgentId?.trim() || item.uninstallAgentId?.trim() || item.id,
    hostname: item.hostname?.trim() || item.displayName?.trim() || item.name.trim() || item.id,
    displayName: item.displayName?.trim() || item.name.trim() || undefined,
    status: item.healthStatus?.trim() || item.status,
    connected: true,
    lastSeen: item.lastSeen || Date.now(),
    agentVersion: item.version?.trim() || undefined,
  },
});

export const useInfrastructureInstallState = (options: InfrastructureInstallStateOptions = {}) => {
  const location = useLocation();
  const navigate = useNavigate();

  let hasLoggedSecurityStatusError = false;

  const [securityStatus, setSecurityStatus] = createSignal<SecurityStatus | null>(null);
  const [latestRecord, setLatestRecord] = createSignal<APITokenRecord | null>(null);
  const [tokenName, setTokenName] = createSignal('');
  const [confirmedNoToken, setConfirmedNoToken] = createSignal(false);
  const [currentToken, setCurrentToken] = createSignal<string | null>(null);
  const [isGeneratingToken, setIsGeneratingToken] = createSignal(false);
  const [lookupValue, setLookupValue] = createSignal('');
  const [lookupResult, setLookupResult] = createSignal<AgentLookupResponse | null>(null);
  const [lookupError, setLookupError] = createSignal<string | null>(null);
  const [lookupLoading, setLookupLoading] = createSignal(false);
  const [autoLookupActive, setAutoLookupActive] = createSignal(false);
  const [lookupWasAutoDetected, setLookupWasAutoDetected] = createSignal(false);
  const [insecureMode, setInsecureMode] = createSignal(false);
  const [enableCommands, setEnableCommands] = createSignal(false);
  const [installProfile, setInstallProfile] = createSignal<InstallProfile>('auto');
  const [customAgentUrl, setCustomAgentUrl] = createSignal('');
  const [customCaPath, setCustomCaPath] = createSignal('');
  const [setupHandoff, setSetupHandoff] = createSignal<SetupHandoffState | null>(null);
  const [latestTokenSource, setLatestTokenSource] = createSignal<'manual' | 'setup_handoff' | null>(
    null,
  );
  const [setupHandoffAutoTokenPending, setSetupHandoffAutoTokenPending] = createSignal(false);
  const [setupHandoffAutoTokenFailed, setSetupHandoffAutoTokenFailed] = createSignal(false);
  const [setupHandoffAutoTokenAttempted, setSetupHandoffAutoTokenAttempted] = createSignal(false);
  let disposed = false;

  onCleanup(() => {
    disposed = true;
  });

  createEffect(() => {
    if (requiresToken()) {
      setConfirmedNoToken(false);
    }
  });

  const agentUrl = () => securityStatus()?.agentUrl || getPulseBaseUrl();
  const selectedAgentUrl = () => resolveInstallerBaseUrl(customAgentUrl(), agentUrl());

  onMount(() => {
    if (typeof window === 'undefined') {
      return;
    }

    const rawSetupHandoff = sessionStorage.getItem(STORAGE_KEYS.SETUP_HANDOFF);
    if (rawSetupHandoff) {
      try {
        const parsed = JSON.parse(rawSetupHandoff) as Partial<SetupHandoffState>;
        if (parsed.username && parsed.apiToken) {
          setSetupHandoff({
            username: parsed.username,
            apiToken: parsed.apiToken,
            createdAt: parsed.createdAt,
          });
        } else {
          sessionStorage.removeItem(STORAGE_KEYS.SETUP_HANDOFF);
        }
      } catch (_err) {
        sessionStorage.removeItem(STORAGE_KEYS.SETUP_HANDOFF);
      }
    }

    const fetchSecurityStatus = async () => {
      try {
        const data = await SecurityAPI.getStatus();
        if (disposed) {
          return;
        }
        setSecurityStatus(data);
      } catch (err) {
        if (disposed) {
          return;
        }
        if (!hasLoggedSecurityStatusError) {
          hasLoggedSecurityStatusError = true;
          logger.error('Failed to load security status', err);
        }
      }
    };

    void fetchSecurityStatus();
  });

  const clearSetupHandoff = () => {
    if (typeof window !== 'undefined') {
      try {
        sessionStorage.removeItem(STORAGE_KEYS.SETUP_HANDOFF);
      } catch (_err) {
        // Ignore storage cleanup failures.
      }
    }
    setSetupHandoff(null);
  };

  const copySetupHandoffField = async (value: string, successMessage: string) => {
    const copied = await copyToClipboard(value);
    if (copied) {
      notificationStore.success(successMessage);
    } else {
      notificationStore.error(getUnifiedAgentClipboardCopyErrorMessage());
    }
  };

  const downloadSetupHandoff = () => {
    const handoff = setupHandoff();
    if (!handoff) return;

    const baseUrl = getPulseBaseUrl();
    const content = `Pulse First-Run Credentials
============================
Generated: ${handoff.createdAt || new Date().toISOString()}

Web Login:
----------
URL: ${baseUrl}
Username: ${handoff.username}
Password: shown once on the setup completion screen and not stored here. If you didn't save it, change it from Settings → Security → Change password.

Admin API Token:
----------------
${handoff.apiToken}

Canonical install workspace:
----------------------------
${baseUrl.replace(/\/$/, '')}${buildInfrastructureOnboardingPath('linux-host')}

Pulse prepares the first-host install token from setup so you can move straight to the generated Unified Agent install commands.
`;

    const blob = new Blob([content], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `pulse-first-run-credentials-${Date.now()}.txt`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  const requiresToken = () => {
    const status = securityStatus();
    if (status) {
      return status.requiresAuth || status.apiTokenConfigured;
    }
    return true;
  };

  const hasToken = () => Boolean(currentToken());
  const commandsUnlocked = () => (requiresToken() ? hasToken() : hasToken() || confirmedNoToken());
  const setupHandoffInstallStepActive = () => {
    const step = deriveAddStepFromLocation(location.pathname, location.search);
    return step !== null && SETUP_HANDOFF_INSTALL_STEPS.has(step);
  };

  const acknowledgeNoToken = () => {
    if (requiresToken()) {
      notificationStore.info('Generate or select a token before continuing.', 4000);
      return;
    }
    setCurrentToken(null);
    setLatestRecord(null);
    setConfirmedNoToken(true);
    notificationStore.success('Confirmed install commands without an API token.', 3500);
  };

  const showCurrentTokenOnly = () => {
    const token = currentToken();
    const record = latestRecord();
    if (!token || !record) return;

    showTokenReveal({
      token,
      record,
      source: 'agent',
      note: INSTALL_TOKEN_REVEAL_NOTE,
    });
  };

  const generateInstallToken = async (
    source: 'manual' | 'setup_handoff',
    options: { notifySuccess?: boolean } = {},
  ): Promise<boolean> => {
    setIsGeneratingToken(true);
    try {
      // The server owns install-token semantics. It decides the scopes from
      // the command-execution choice at mint time (scopes cannot be upgraded
      // on an existing token) and stamps the metadata the command channel
      // needs for first-use binding (#1586).
      const withCommands = enableCommands();
      const desiredName = tokenName().trim() || buildDefaultTokenName();
      const { token, record } = await NodesAPI.createHostAgentInstallToken({
        enableCommands: withCommands,
        name: desiredName,
      });

      if (disposed) {
        return false;
      }
      setCurrentToken(token);
      setLatestRecord(record);
      setLatestTokenSource(source);
      setTokenName('');
      setConfirmedNoToken(false);
      setSetupHandoffAutoTokenFailed(false);
      if (source === 'manual') {
        showTokenReveal({
          token,
          record,
          source: 'agent',
          note: INSTALL_TOKEN_REVEAL_NOTE,
        });
      }
      if (options.notifySuccess) {
        notificationStore.success(
          withCommands
            ? 'Token generated with Agent config, reporting, Docker, Kubernetes, and command execution permissions.'
            : 'Token generated with Agent config, reporting, Docker, and Kubernetes permissions.',
          4000,
        );
      }
      return true;
    } catch (err) {
      if (disposed) {
        return false;
      }
      logger.error('Failed to generate agent token', err);
      if (source === 'setup_handoff') {
        setSetupHandoffAutoTokenFailed(true);
      } else {
        notificationStore.error(
          'Failed to generate agent token. Confirm you are signed in as an administrator.',
          6000,
        );
      }
      return false;
    } finally {
      if (!disposed) {
        setIsGeneratingToken(false);
        if (source === 'setup_handoff') {
          setSetupHandoffAutoTokenPending(false);
        }
      }
    }
  };

  const handleGenerateToken = async () => {
    if (isGeneratingToken()) return;

    await generateInstallToken('manual', { notifySuccess: true });
  };

  // Toggling command execution changes which scopes the token needs, and an
  // already-minted token cannot be upgraded. Regenerate it so the copied
  // command always carries a token that matches the checkbox (#1586).
  const handleEnableCommandsChange = async (value: boolean): Promise<void> => {
    if (value === enableCommands()) return;
    if (isGeneratingToken()) {
      notificationStore.info(
        'Wait for the current token to finish generating, then try again.',
        4000,
      );
      return;
    }

    const previousEnableCommands = enableCommands();
    const supersededToken = currentToken();
    const supersededRecord = latestRecord();
    const source = latestTokenSource() ?? 'manual';
    setEnableCommands(value);
    if (!supersededToken) return;

    // Token scope and rendered flags are one atomic command state. Lock the
    // command surface before minting so --enable-commands can never be copied
    // with the previous non-exec token (or the inverse).
    setCurrentToken(null);
    setLatestRecord(null);
    const generated = await generateInstallToken(source, { notifySuccess: false });
    if (disposed) return;

    if (!generated) {
      // Restore the complete previous state; never leave new flags paired with
      // the old credential after a failed replacement.
      setEnableCommands(previousEnableCommands);
      setCurrentToken(supersededToken);
      setLatestRecord(supersededRecord);
      return;
    }

    notificationStore.info(
      value
        ? 'New token prepared with command execution permission. Existing tokens remain valid. Rerun the install command on the intended host.'
        : 'New token prepared without command execution permission. Existing tokens remain valid. Rerun the install command on the intended host.',
      5000,
    );
    // A displayed token may already be installed on a reporting host. Preparing
    // a different scope does not prove it is unused and must not revoke it.
    // Deliberate revocation stays in Tokens, after the operator checks its use.
  };

  const resolvedCommandToken = () => {
    if (requiresToken()) {
      return currentToken() || TOKEN_PLACEHOLDER;
    }
    return currentToken();
  };

  createEffect(() => {
    const shouldAutoCreateInstallToken =
      Boolean(setupHandoff()) &&
      setupHandoffInstallStepActive() &&
      securityStatus() !== null &&
      requiresToken() &&
      !currentToken() &&
      !latestRecord() &&
      !isGeneratingToken() &&
      !setupHandoffAutoTokenAttempted();

    if (!shouldAutoCreateInstallToken) {
      return;
    }

    setSetupHandoffAutoTokenAttempted(true);
    setSetupHandoffAutoTokenPending(true);
    void generateInstallToken('setup_handoff');
  });

  createEffect(() => {
    const shouldAutoDetectFirstHost =
      commandsUnlocked() && !lookupValue().trim() && !lookupResult()?.agent?.connected;

    if (!shouldAutoDetectFirstHost) {
      setAutoLookupActive(false);
      return;
    }

    let baselineActiveCount: number | null = null;
    let pollInterval: number | undefined;
    let cancelled = false;

    const pollForFirstHost = async () => {
      try {
        const state = await MonitoringAPI.getState();
        if (cancelled) {
          return;
        }

        const activeItems = (state.connectedInfrastructure || []).filter(
          isActiveInfrastructureItem,
        );
        if (baselineActiveCount === null) {
          baselineActiveCount = activeItems.length;
        }

        const shouldKeepWatching = baselineActiveCount === 0 && activeItems.length === 0;
        setAutoLookupActive(shouldKeepWatching);

        if (baselineActiveCount !== 0 || activeItems.length === 0) {
          return;
        }

        const detectedItem = pickMostRecentInfrastructureItem(activeItems);
        if (!detectedItem) {
          return;
        }

        const detectedLookup = toLookupResponseFromInfrastructureItem(detectedItem);
        setLookupResult(detectedLookup);
        setLookupError(null);
        setLookupWasAutoDetected(true);
        setLookupValue(detectedLookup.agent?.hostname || detectedLookup.agent?.id || '');
        setAutoLookupActive(false);

        if (pollInterval) {
          window.clearInterval(pollInterval);
          pollInterval = undefined;
        }
      } catch (err) {
        if (!cancelled) {
          logger.warn('Failed to auto-detect first connected host', err);
        }
      }
    };

    void pollForFirstHost();
    pollInterval = window.setInterval(pollForFirstHost, FIRST_HOST_AUTODETECT_POLL_MS);

    onCleanup(() => {
      cancelled = true;
      setAutoLookupActive(false);
      if (pollInterval) {
        window.clearInterval(pollInterval);
      }
    });
  });

  const handleLookup = async () => {
    const query = lookupValue().trim();
    setLookupError(null);
    setLookupWasAutoDetected(false);

    if (!query) {
      setLookupResult(null);
      setLookupError('Enter a hostname or agent ID to check.');
      return;
    }

    setLookupLoading(true);
    try {
      const result = await MonitoringAPI.lookupAgent({ id: query, hostname: query });
      if (!result) {
        setLookupResult(null);
        setLookupError(`No agent has reported with "${query}" yet. Try again in a few seconds.`);
      } else {
        setLookupResult(result);
        setLookupError(null);
      }
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Agent lookup failed.';
      setLookupResult(null);
      setLookupError(message);
    } finally {
      setLookupLoading(false);
    }
  };

  const clearLookupState = () => {
    setLookupError(null);
    setLookupResult(null);
    setLookupWasAutoDetected(false);
  };

  const selectedCustomCaPath = () => customCaPath().trim();
  const getSelectedInstallProfile = () =>
    INSTALL_PROFILE_OPTIONS.find((option) => option.value === installProfile()) ??
    INSTALL_PROFILE_OPTIONS[0];
  const getInstallProfileFlags = () => getSelectedInstallProfile().flags;
  const getPowerShellInstallEnv = () => {
    const envAssignments = getPowerShellInstallProfileEnvFromFlags(getInstallProfileFlags());
    if (enableCommands()) {
      envAssignments.push(`$env:PULSE_ENABLE_COMMANDS="true"`);
    }
    return envAssignments;
  };
  const getInstallerExtraArgs = () => [
    ...getInstallProfileFlags(),
    ...(enableCommands() ? ['--enable-commands'] : []),
  ];

  const handleInstallProfileChange = (profile: InstallProfile) => {
    setInstallProfile(profile);
  };

  const commandSections = createMemo(() => {
    const url = selectedAgentUrl();
    const token = resolvedCommandToken();
    const unixCommand = buildUnixAgentInstallCommand({
      baseUrl: url,
      token,
      insecure: insecureMode(),
      caCertPath: selectedCustomCaPath(),
      extraArgs: getInstallerExtraArgs(),
    });
    const windowsInteractiveCommand = buildWindowsAgentInstallCommand({
      baseUrl: url,
      token: currentToken(),
      insecure: insecureMode(),
      caCertPath: selectedCustomCaPath(),
      extraEnvAssignments: getPowerShellInstallEnv(),
    });
    const windowsParameterizedCommand = buildWindowsAgentInstallCommand({
      baseUrl: url,
      token,
      insecure: insecureMode(),
      caCertPath: selectedCustomCaPath(),
      extraEnvAssignments: getPowerShellInstallEnv(),
    });
    const commands = buildCommandsByPlatform(
      unixCommand,
      windowsInteractiveCommand,
      windowsParameterizedCommand,
      token
        ? buildUnixAgentInstallCommand({
            baseUrl: url,
            tokenFilePath: '/root/.config/pulse-agent/bootstrap-token',
            insecure: insecureMode(),
            caCertPath: selectedCustomCaPath(),
            extraArgs: getInstallerExtraArgs(),
          })
        : undefined,
    );
    return Object.entries(commands).map(([platform, meta]) => ({
      platform: platform as AgentPlatform,
      ...meta,
    }));
  });

  const openInfrastructure = () => {
    navigate(buildInfrastructureWorkspacePath());
  };

  const openInfrastructureInventory = () => {
    navigate(buildInfrastructureWorkspacePath());
  };

  const isEmbedded = () => options.embedded ?? false;

  return {
    acknowledgeNoToken,
    agentUrl,
    autoLookupActive,
    clearLookupState,
    clearSetupHandoff,
    commandSections,
    commandsUnlocked,
    confirmedNoToken,
    copySetupHandoffField,
    currentToken,
    customAgentUrl,
    customCaPath,
    downloadSetupHandoff,
    enableCommands,
    getInstallProfileFlags,
    getSelectedInstallProfile,
    handleGenerateToken,
    handleInstallProfileChange,
    handleLookup,
    hasToken,
    insecureMode,
    installProfile,
    isEmbedded,
    isGeneratingToken,
    latestRecord,
    latestTokenSource,
    lookupError,
    lookupLoading,
    lookupResult,
    lookupValue,
    lookupWasAutoDetected,
    openInfrastructure,
    openInfrastructureInventory,
    requiresToken,
    selectedAgentUrl,
    setCustomAgentUrl,
    setCustomCaPath,
    setEnableCommands: handleEnableCommandsChange,
    setInsecureMode,
    setLookupValue,
    setTokenName,
    setupHandoff,
    setupHandoffAutoTokenFailed,
    setupHandoffAutoTokenPending,
    showCurrentTokenOnly,
    tokenName,
  };
};