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.

13.2 KB
Raw Blame
import type { Component } from 'solid-js';
import Shield from 'lucide-solid/icons/shield';
import ShieldAlert from 'lucide-solid/icons/shield-alert';
import ShieldCheck from 'lucide-solid/icons/shield-check';

export interface SecurityScoreTonePresentation {
  headerBg: string;
  headerBorder: string;
  iconWrap: string;
  icon: string;
  subtitle: string;
  score: string;
  badge: string;
}

export interface SecurityScorePresentation {
  label: 'Strong' | 'Moderate' | 'Weak';
  tone: SecurityScoreTonePresentation;
  icon: 'shield-check' | 'shield' | 'shield-alert';
}

export interface SecurityWarningPresentation {
  background: string;
  border: string;
  message: string;
  messageClass: string;
}

/**
 * How much of the security posture `/api/security/status` was willing to tell
 * this caller. The endpoint truncates by authority: `public` carries login
 * discovery and authentication state only, `authenticated` adds session
 * identity but still no posture fields, and only `privileged` (settings:read)
 * carries exportProtected, apiTokenConfigured, hasHTTPS, publicAccess and the
 * rest.
 */
export type SecurityStatusDetailLevel = 'public' | 'authenticated' | 'privileged';

export interface SecurityRuntimeWarningVisibilityOptions {
  detailLevel?: SecurityStatusDetailLevel;
  hasAuthentication: boolean;
  exportProtected: boolean;
  hasHTTPS?: boolean;
  publicAccess?: boolean;
}

export interface SecurityFeatureStatePresentation {
  label: 'Yes' | 'No';
  className: string;
}

export interface SecurityFeatureCardPresentation {
  cardClassName: string;
  iconClassName: string;
  statusLabel: 'Enabled' | 'Disabled';
  criticalLabelClassName: string;
}

export type SecurityHardeningActionKey =
  'enable-authentication' | 'protect-exports' | 'configure-https' | 'create-api-token';

export interface SecurityHardeningAction {
  key: SecurityHardeningActionKey;
  severity: 'critical' | 'recommended';
  title: string;
  description: string;
}

export interface SecurityPostureStatus {
  hasAuthentication: boolean;
  ssoEnabled?: boolean;
  hasProxyAuth?: boolean;
  apiTokenConfigured: boolean;
  exportProtected: boolean;
  unprotectedExportAllowed?: boolean;
  hasHTTPS?: boolean;
  hasAuditLogging: boolean;
  requiresAuth: boolean;
  publicAccess?: boolean;
  isPrivateNetwork?: boolean;
  clientIP?: string;
}

export interface SecurityPostureItem {
  key: 'password' | 'oidc' | 'proxy' | 'token' | 'export' | 'https' | 'audit';
  label: string;
  enabled: boolean;
  description: string;
  critical: boolean;
}

export function getSecurityScorePresentation(score: number): SecurityScorePresentation {
  if (score >= 80) {
    return {
      label: 'Strong',
      icon: 'shield-check',
      tone: {
        headerBg: 'bg-emerald-50 dark:bg-emerald-950/25',
        headerBorder: 'border-b border-emerald-200 dark:border-emerald-800',
        iconWrap: 'bg-emerald-100 dark:bg-emerald-900/25',
        icon: 'text-emerald-700 dark:text-emerald-300',
        subtitle: 'text-emerald-700 dark:text-emerald-300',
        score: 'text-emerald-800 dark:text-emerald-200',
        badge: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/25 dark:text-emerald-300',
      },
    };
  }

  if (score >= 50) {
    return {
      label: 'Moderate',
      icon: 'shield',
      tone: {
        headerBg: 'bg-amber-50 dark:bg-amber-950/25',
        headerBorder: 'border-b border-amber-200 dark:border-amber-800',
        iconWrap: 'bg-amber-100 dark:bg-amber-900/25',
        icon: 'text-amber-700 dark:text-amber-300',
        subtitle: 'text-amber-700 dark:text-amber-300',
        score: 'text-amber-800 dark:text-amber-200',
        badge: 'bg-amber-100 text-amber-700 dark:bg-amber-900/25 dark:text-amber-300',
      },
    };
  }

  return {
    label: 'Weak',
    icon: 'shield-alert',
    tone: {
      headerBg: 'bg-rose-50 dark:bg-rose-950/25',
      headerBorder: 'border-b border-rose-200 dark:border-rose-800',
      iconWrap: 'bg-rose-100 dark:bg-rose-900/25',
      icon: 'text-rose-700 dark:text-rose-300',
      subtitle: 'text-rose-700 dark:text-rose-300',
      score: 'text-rose-800 dark:text-rose-200',
      badge: 'bg-rose-100 text-rose-700 dark:bg-rose-900/25 dark:text-rose-300',
    },
  };
}

export function getSecurityWarningPresentation(options: {
  score: number;
  publicAccess: boolean;
  hasAuthentication: boolean;
  apiTokenConfigured: boolean;
  exportProtected: boolean;
  hasHTTPS?: boolean;
}): SecurityWarningPresentation {
  if (options.publicAccess && !options.hasAuthentication) {
    return {
      background: 'bg-red-50 dark:bg-red-900/25',
      border: 'border-red-200 dark:border-red-800',
      message:
        'WARNING: PUBLIC NETWORK ACCESS DETECTED - Your Proxmox credentials are exposed to the internet!',
      messageClass: 'font-semibold text-red-700 dark:text-red-300',
    };
  }

  const posture = getSecurityScorePresentation(options.score);
  const missingControls: string[] = [];
  if (!options.hasHTTPS) {
    missingControls.push('HTTPS');
  }
  if (!options.apiTokenConfigured) {
    missingControls.push('an API token');
  }
  if (!options.exportProtected) {
    missingControls.push('protected exports');
  }

  const formatList = (items: string[]): string => {
    if (items.length <= 1) {
      return items[0] ?? 'required security controls';
    }
    if (items.length === 2) {
      return `${items[0]} and ${items[1]}`;
    }
    return `${items.slice(0, -1).join(', ')}, and ${items[items.length - 1]}`;
  };

  let message =
    'Review the remaining security settings before using this instance for live infrastructure.';
  if (!options.hasAuthentication) {
    message =
      'Authentication is disabled. Anyone who can reach this Pulse instance can access stored infrastructure credentials.';
  } else if (missingControls.length > 0) {
    const missingSummary = formatList(missingControls);
    message = options.publicAccess
      ? `This Pulse instance is reachable from a public network and is still missing ${missingSummary}.`
      : `Authentication is enabled, but this Pulse instance is still missing ${missingSummary}.`;
  }

  return {
    background:
      posture.label === 'Moderate'
        ? 'bg-yellow-50 dark:bg-yellow-900/25'
        : 'bg-red-50 dark:bg-red-900/25',
    border:
      posture.label === 'Moderate'
        ? 'border-yellow-200 dark:border-yellow-800'
        : 'border-red-200 dark:border-red-800',
    message,
    messageClass: 'text-base-content',
  };
}

/**
 * The global banner may only be raised from fields the payload actually
 * carries. A truncated response omits the posture fields entirely, and reading
 * an absent field as `false` is how a kiosk token (monitoring:read only) was
 * shown a bogus "security score 1/5" banner linking into settings it cannot
 * open (#1650).
 *
 * - `authenticated`: no posture fields at all, so nothing can be asserted.
 * - `public`: only `hasAuthentication` is authoritative, which is exactly the
 *   case that matters — an instance with no authentication configured must
 *   still be warned about.
 * - `privileged` (or a caller supplying the full posture directly): full
 *   assessment.
 */
export function shouldShowGlobalSecurityWarning(
  options: SecurityRuntimeWarningVisibilityOptions,
): boolean {
  const detailLevel = options.detailLevel ?? 'privileged';

  if (detailLevel === 'authenticated') {
    return false;
  }

  if (!options.hasAuthentication) {
    return true;
  }

  if (detailLevel === 'public') {
    return false;
  }

  if (!options.exportProtected) {
    return true;
  }

  return Boolean(options.publicAccess && !options.hasHTTPS);
}

export function getSecurityScoreTextClass(score: number): string {
  return getSecurityScorePresentation(score).tone.icon;
}

export function getSecurityFeatureStatePresentation(
  enabled: boolean,
): SecurityFeatureStatePresentation {
  return {
    label: enabled ? 'Yes' : 'No',
    className: enabled ? 'text-green-600' : 'text-red-600',
  };
}

export function getSecurityScoreIconComponent(score: number): Component<{ class?: string }> {
  switch (getSecurityScorePresentation(score).icon) {
    case 'shield-check':
      return ShieldCheck;
    case 'shield':
      return Shield;
    default:
      return ShieldAlert;
  }
}

export function getSecurityFeatureCardPresentation(options: {
  enabled: boolean;
  critical: boolean;
}): SecurityFeatureCardPresentation {
  if (options.enabled) {
    return {
      cardClassName:
        'border-emerald-200 dark:border-emerald-800 bg-emerald-50 dark:bg-emerald-950/25',
      iconClassName: 'text-emerald-500 dark:text-emerald-400',
      statusLabel: 'Enabled',
      criticalLabelClassName: 'text-emerald-600 dark:text-emerald-400',
    };
  }

  if (options.critical) {
    return {
      cardClassName: 'border-rose-200 dark:border-rose-800 bg-rose-50 dark:bg-rose-950/25',
      iconClassName: 'text-rose-500 dark:text-rose-400',
      statusLabel: 'Disabled',
      criticalLabelClassName: 'text-rose-600 dark:text-rose-400',
    };
  }

  return {
    cardClassName: 'border-border bg-surface-alt',
    iconClassName: 'text-muted',
    statusLabel: 'Disabled',
    criticalLabelClassName: 'text-muted',
  };
}

export function getSecurityHardeningActions(
  status: SecurityPostureStatus,
): SecurityHardeningAction[] {
  const actions: SecurityHardeningAction[] = [];

  if (!status.hasAuthentication) {
    actions.push({
      key: 'enable-authentication',
      severity: 'critical',
      title: 'Enable authentication',
      description:
        'Anyone who can reach this Pulse instance can sign in without a password boundary until authentication is configured.',
    });
  }

  if (!status.exportProtected || status.unprotectedExportAllowed) {
    actions.push({
      key: 'protect-exports',
      severity: 'critical',
      title: 'Protect exports',
      description:
        'Backup and export flows are currently allowed without token-backed protection. Lock them down before using this instance for real infrastructure data.',
    });
  }

  if (status.publicAccess && !status.hasHTTPS) {
    actions.push({
      key: 'configure-https',
      severity: 'critical',
      title: 'Enable HTTPS for public access',
      description:
        'This Pulse instance is reachable from a public network and still serves over HTTP. Put it behind TLS before exposing it beyond your private network.',
    });
  } else if (!status.hasHTTPS) {
    actions.push({
      key: 'configure-https',
      severity: 'recommended',
      title: 'Plan HTTPS before live use',
      description:
        'Local HTTP is acceptable for development, but production access should terminate TLS at a reverse proxy before operators use this instance for live infrastructure.',
    });
  }

  if (status.hasAuthentication && !status.apiTokenConfigured) {
    actions.push({
      key: 'create-api-token',
      severity: 'recommended',
      title: 'Create an API token',
      description:
        'Scoped API tokens protect export and automation flows without reusing the interactive admin password.',
    });
  }

  return actions;
}

export function getSecurityPostureItems(status: SecurityPostureStatus): SecurityPostureItem[] {
  return [
    {
      key: 'password',
      label: 'Password login',
      enabled: status.hasAuthentication,
      description: status.hasAuthentication ? 'Active' : 'Not configured',
      critical: true,
    },
    {
      key: 'oidc',
      label: 'Single sign-on',
      enabled: Boolean(status.ssoEnabled),
      description: status.ssoEnabled ? 'Provider configured' : 'Not configured',
      critical: false,
    },
    {
      key: 'proxy',
      label: 'Proxy auth',
      enabled: Boolean(status.hasProxyAuth),
      description: status.hasProxyAuth ? 'Active' : 'Not configured',
      critical: false,
    },
    {
      key: 'token',
      label: 'API token',
      enabled: status.apiTokenConfigured,
      description: status.apiTokenConfigured ? 'Active' : 'Not configured',
      critical: false,
    },
    {
      key: 'export',
      label: 'Export protection',
      enabled: status.exportProtected && !status.unprotectedExportAllowed,
      description: status.unprotectedExportAllowed ? 'Unprotected' : 'Token + passphrase required',
      critical: true,
    },
    {
      key: 'https',
      label: 'HTTPS',
      enabled: Boolean(status.hasHTTPS),
      description: status.hasHTTPS ? 'Encrypted' : 'HTTP only',
      // Same rule as the hardening steps below the grid: plain HTTP is
      // critical once the instance is publicly reachable, and a recommended
      // step on a private network. Marking it critical there put a red
      // Critical tile above a Recommended card for the same control.
      critical: Boolean(status.publicAccess),
    },
    {
      key: 'audit',
      label: 'Audit log',
      enabled: status.hasAuditLogging,
      description: status.hasAuditLogging ? 'Active' : 'Not enabled',
      critical: false,
    },
  ];
}

export function getSecurityNetworkAccessSubtitle(status: SecurityPostureStatus): string {
  return status.publicAccess && !status.isPrivateNetwork
    ? 'Public network access detected'
    : 'Private network access';
}

export function getSecurityScoreSymbol(score: number): '✓' | '!' | '!!' {
  switch (getSecurityScorePresentation(score).icon) {
    case 'shield-check':
      return '✓';
    case 'shield':
      return '!';
    default:
      return '!!';
  }
}