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.9 KB
Raw Blame
import { Show } from 'solid-js';
import Shield from 'lucide-solid/icons/shield';
import RefreshCw from 'lucide-solid/icons/refresh-cw';
import Info from 'lucide-solid/icons/info';
import Play from 'lucide-solid/icons/play';
import ShieldAlert from 'lucide-solid/icons/shield-alert';
import { Button } from '@/components/shared/Button';
import { EmptyState } from '@/components/shared/EmptyState';
import { showTooltip, hideTooltip } from '@/components/shared/Tooltip';
import { UpgradeButtonLink } from '@/components/shared/UpgradeLink';
import { FilterBar, type FilterDef, type FilterSelectOption } from '@/components/shared/FilterBar';
import { FormSelect } from '@/components/shared/FormSelect';
import Toggle from '@/components/shared/Toggle';
import SettingsPanel from '@/components/shared/SettingsPanel';
import { PulseDataGrid } from '@/components/shared/PulseDataGrid';
import { useBreakpoint } from '@/hooks/useBreakpoint';
import {
  AUDIT_REFRESH_BUTTON_CLASS,
  AUDIT_VERIFY_ALL_BUTTON_CLASS,
  AUDIT_VERIFY_ROW_BUTTON_CLASS,
  AUDIT_TOOLBAR_BUTTON_CLASS,
  AUDIT_EVENT_CONFIG_CHANGE_LABEL,
  AUDIT_EVENT_FILTER_ALL_LABEL,
  AUDIT_SUCCESS_FILTER_FAILED_ONLY_LABEL,
  AUDIT_SUCCESS_FILTER_SUCCESS_ONLY_LABEL,
  AUDIT_VERIFICATION_FILTER_ALL_LABEL,
  AUDIT_VERIFICATION_FILTER_NEEDS_LABEL,
  getAuditEventStatusPresentation,
  getAuditEventTypeBadgeClass,
  getAuditLogFeatureGateCopy,
  getAuditLogEmptyState,
  getAuditLogLoadingState,
  getAuditVerificationBadgePresentation,
} from '@/utils/auditLogPresentation';
import {
  useAuditLogPanelState,
  type AuditLogPanelProps,
} from '@/components/Settings/useAuditLogPanelState';
import { InlineNotice } from '@/components/shared/InlineNotice';

export default function AuditLogPanel(props: AuditLogPanelProps) {
  const { isMobile } = useBreakpoint();
  const {
    accessAllowed,
    activeFilterCount,
    auditLoggingEnabled,
    autoVerifyEnabled,
    autoVerifyLimit,
    cancelVerification,
    clearFilters,
    error,
    eventFilter,
    filteredEvents,
    goToFirstPage,
    goToLastPage,
    goToNextPage,
    goToPreviousPage,
    hasNextPage,
    hasResumeEvents,
    hasSignedEvents,
    isPersistent,
    loading,
    pageInput,
    pageNumber,
    pageRangeText,
    pageSize,
    refresh,
    resumeCount,
    resumeVerification,
    resetPreferences,
    setAutoVerifyEnabled,
    setAutoVerifyLimit,
    setEventFilter,
    setPageInput,
    setPageSize,
    setSuccessFilter,
    setUserFilter,
    setVerificationFilter,
    showUpgradePaywall,
    showFeatureGateAction,
    submitPageInput,
    successFilter,
    totalEvents,
    totalPages,
    upgradeDestination,
    upgradeActionLabel,
    paidRuntimeRequired,
    verification,
    verificationFilter,
    verificationSummary,
    verificationNotice,
    verifyAll,
    verifyAllLabel,
    verifyCanceled,
    verifyEvent,
    verifying,
    verifyingAll,
    userFilter,
  } = useAuditLogPanelState(props);

  const formatTimestamp = (ts: string) => {
    const date = new Date(ts);
    return date.toLocaleString();
  };
  const featureGateCopy = () =>
    getAuditLogFeatureGateCopy({ paidRuntimeRequired: paidRuntimeRequired() });

  const auditEventOptions = (): FilterSelectOption[] => [
    { value: '', label: AUDIT_EVENT_FILTER_ALL_LABEL },
    { value: 'login', label: 'Login' },
    { value: 'logout', label: 'Logout' },
    { value: 'config_change', label: AUDIT_EVENT_CONFIG_CHANGE_LABEL },
    { value: 'startup', label: 'Startup' },
  ];
  const auditSuccessOptions = (): FilterSelectOption[] => [
    { value: 'all', label: 'All' },
    { value: 'success', label: AUDIT_SUCCESS_FILTER_SUCCESS_ONLY_LABEL },
    { value: 'failed', label: AUDIT_SUCCESS_FILTER_FAILED_ONLY_LABEL },
  ];
  const auditVerificationOptions = (): FilterSelectOption[] => [
    { value: 'all', label: AUDIT_VERIFICATION_FILTER_ALL_LABEL },
    { value: 'needs', label: AUDIT_VERIFICATION_FILTER_NEEDS_LABEL },
    { value: 'verified', label: 'Verified' },
    { value: 'failed', label: 'Failed/Error' },
  ];

  const buildAuditFilters = (): FilterDef[] => [
    {
      id: 'audit-event',
      label: 'Event',
      group: 'properties',
      value: eventFilter,
      setValue: setEventFilter,
      defaultValue: '',
      options: auditEventOptions,
    },
    {
      id: 'audit-success',
      label: 'Outcome',
      group: 'status',
      value: successFilter,
      setValue: setSuccessFilter,
      defaultValue: 'all',
      options: auditSuccessOptions,
    },
    {
      id: 'audit-verification',
      label: 'Verification',
      group: 'status',
      value: verificationFilter,
      setValue: setVerificationFilter,
      defaultValue: 'all',
      options: auditVerificationOptions,
    },
  ];

  return (
    <SettingsPanel
      title="Audit Log"
      noPadding
      bodyClass="space-y-6 p-4 sm:p-6"
      action={
        <div class="flex w-full flex-wrap items-center gap-2 sm:w-auto">
          <button
            onClick={refresh}
            disabled={loading() || !accessAllowed()}
            class={AUDIT_REFRESH_BUTTON_CLASS}
          >
            <RefreshCw class={`w-4 h-4 ${loading() ? 'animate-spin' : ''}`} />
            Refresh
          </button>
          <button
            onClick={verifyAll}
            disabled={!isPersistent() || loading() || verifyingAll() || !hasSignedEvents()}
            class={AUDIT_VERIFY_ALL_BUTTON_CLASS}
          >
            {(() => {
              const presentation = getAuditEventStatusPresentation(true);
              const Icon = presentation.icon;
              return <Icon class="w-4 h-4" />;
            })()}
            {verifyAllLabel()}
          </button>
          <button
            onClick={cancelVerification}
            disabled={!verifyingAll()}
            class={`${AUDIT_TOOLBAR_BUTTON_CLASS} text-muted`}
          >
            Cancel
          </button>
          <button
            onClick={resumeVerification}
            disabled={verifyingAll() || !hasResumeEvents()}
            class={`${AUDIT_TOOLBAR_BUTTON_CLASS} text-muted`}
            onMouseEnter={(e) => {
              if (!hasResumeEvents()) return;
              const rect = e.currentTarget.getBoundingClientRect();
              showTooltip(
                'Retries failed, error, or unchecked signatures on this page.',
                rect.left + rect.width / 2,
                rect.top,
                { align: 'center', direction: 'up', maxWidth: 260 },
              );
            }}
            onMouseLeave={() => hideTooltip()}
          >
            <Play class="w-4 h-4" />
            Resume{resumeCount() > 0 ? ` (${resumeCount()})` : ''}
          </button>
          <Show when={verifyCanceled() && !verifyingAll()}>
            <span class="text-xs text-amber-600 dark:text-amber-400">Verification canceled</span>
          </Show>
        </div>
      }
    >
      <Show when={showUpgradePaywall()}>
        <div class="p-6 bg-surface-alt border border-border rounded-md">
          <div class="flex flex-col sm:flex-row items-center gap-4">
            <div class="flex-1">
              <h3 class="text-lg font-semibold text-base-content">{featureGateCopy().title}</h3>
              <p class="text-sm text-muted mt-1">{featureGateCopy().body}</p>
            </div>
            <Show when={showFeatureGateAction()}>
              <div class="flex flex-col items-center gap-2">
                <UpgradeButtonLink
                  destination={upgradeDestination()}
                  mobileFullWidth={false}
                  tone={paidRuntimeRequired() ? 'warning' : 'primary'}
                >
                  {upgradeActionLabel()}
                </UpgradeButtonLink>
              </div>
            </Show>
          </div>
        </div>
      </Show>

      <Show when={isPersistent()}>
        <FilterBar
          role="group"
          ariaLabel="Audit log filters"
          isMobile={isMobile}
          search={{
            value: userFilter,
            setValue: setUserFilter,
            placeholder: 'Filter by user...',
          }}
          filters={buildAuditFilters()}
          viewOptions={
            <div>
              <div class="mb-1.5 text-[10px] font-semibold uppercase tracking-wide text-muted">
                Pagination
              </div>
              <FormSelect
                label="Audit page size"
                labelClass="sr-only"
                fieldBaseClass="contents"
                value={String(pageSize())}
                onChange={(e) => setPageSize(Number(e.currentTarget.value))}
                selectBaseClass="min-h-9 w-full px-2.5 py-1.5 text-xs border border-border rounded-md bg-surface text-base-content"
              >
                <option value="25">25 / page</option>
                <option value="50">50 / page</option>
                <option value="100">100 / page</option>
                <option value="200">200 / page</option>
              </FormSelect>
            </div>
          }
          onClearAll={clearFilters}
          showClearAll={() => activeFilterCount() > 0}
        />
      </Show>

      {/* Verification Preferences */}
      <Show when={isPersistent()}>
        <div class="flex flex-col gap-4 px-1 lg:flex-row lg:items-center lg:justify-between">
          <Toggle
            label="Auto-verify signatures"
            description="Verify signatures after loading audit events."
            checked={autoVerifyEnabled()}
            onChange={(e) => setAutoVerifyEnabled(e.currentTarget.checked)}
          />
          <div class="flex flex-col gap-2 text-xs text-muted sm:flex-row sm:flex-wrap sm:items-center">
            <label class="flex items-center gap-2">
              <span>Auto-verify limit</span>
              <input
                type="number"
                min="0"
                value={autoVerifyLimit()}
                disabled={!autoVerifyEnabled()}
                onInput={(e) => {
                  const raw = Number(e.currentTarget.value);
                  if (!Number.isFinite(raw)) {
                    setAutoVerifyLimit(0);
                    return;
                  }
                  const clamped = Math.max(0, Math.min(500, Math.floor(raw)));
                  setAutoVerifyLimit(clamped);
                }}
                class="min-h-10 sm:min-h-10 w-24 rounded-md border border-border bg-surface px-2.5 py-2 text-sm text-base-content"
              />
            </label>
            <span class="text-muted">0 disables, max 500</span>
            <span
              class="inline-flex items-center cursor-help"
              onMouseEnter={(e) => {
                const rect = e.currentTarget.getBoundingClientRect();
                showTooltip(
                  'Large verification batches can add load. Use a smaller limit on busy systems.',
                  rect.left + rect.width / 2,
                  rect.top,
                  { align: 'center', direction: 'up', maxWidth: 260 },
                );
              }}
              onMouseLeave={() => hideTooltip()}
            >
              <Info class="w-3 h-3" />
            </span>
            <button
              onClick={resetPreferences}
              class="w-full sm:w-auto sm:ml-2 min-h-10 sm:min-h-10 px-3 py-2 text-sm font-medium text-muted border border-border rounded-md hover:bg-surface-hover"
            >
              Reset preferences
            </button>
          </div>
        </div>
      </Show>

      <Show when={!loading() && auditLoggingEnabled() && !accessAllowed()}>
        <InlineNotice tone="warning" role="status">
          Audit log is unavailable for this session.
        </InlineNotice>
      </Show>

      <Show when={verificationNotice()}>
        {(notice) => (
          <InlineNotice tone={notice().tone} role="status" aria-live="polite">
            {notice().message}
          </InlineNotice>
        )}
      </Show>

      <Show when={error()}>
        <div
          role="alert"
          aria-live="assertive"
          class="p-4 bg-red-50 dark:bg-red-900/25 border border-red-200 dark:border-red-800 rounded-md text-red-700 dark:text-red-300"
        >
          {error()}
        </div>
      </Show>

      <Show when={loading()}>
        <div class="flex items-center justify-center py-12">
          <RefreshCw class="w-8 h-8 text-blue-500 animate-spin" />
          <span class="sr-only">{getAuditLogLoadingState().text}</span>
        </div>
      </Show>

      <Show when={!loading() && isPersistent() && filteredEvents().length > 0}>
        <div class="flex flex-wrap items-center gap-3 text-xs text-muted">
          <span>Total: {totalEvents()}</span>
          <span>Signed: {verificationSummary().signed}</span>
          <span>Verified: {verificationSummary().verified}</span>
          <span>Failed: {verificationSummary().failed}</span>
          <span>Errors: {verificationSummary().error}</span>
          <span>Unavailable: {verificationSummary().unavailable}</span>
          <span>Unchecked: {verificationSummary().unchecked}</span>
          <span
            class="inline-flex items-center gap-1 text-muted cursor-help"
            onMouseEnter={(e) => {
              const rect = e.currentTarget.getBoundingClientRect();
              const content = [
                'Unsigned: no signature stored for this event',
                'Unavailable: verification not supported by the logger',
                'Not checked: signature exists but has not been verified',
                'Failed: signature mismatch or tampering detected',
                'Error: verification request failed',
              ].join('\n');
              showTooltip(content, rect.left + rect.width / 2, rect.top, {
                align: 'center',
                direction: 'up',
                maxWidth: 320,
              });
            }}
            onMouseLeave={() => hideTooltip()}
          >
            <Info class="w-3 h-3" />
            Legend
          </span>
          <span class="w-full sm:w-auto sm:ml-auto text-muted">
            {pageRangeText()} • Page {pageNumber()} of {totalPages()}
          </span>
        </div>
        <div class="mt-4">
          <PulseDataGrid
            data={filteredEvents()}
            columns={[
              {
                key: 'success',
                label: 'Status',
                width: '64px',
                align: 'center',
                hiddenOnMobile: true,
                render: (event) => {
                  const presentation = getAuditEventStatusPresentation(event.success);
                  const Icon = presentation.icon;
                  return <Icon class={presentation.className} />;
                },
              },
              {
                key: 'timestamp',
                label: 'Timestamp',
                hiddenOnMobile: true,
                render: (event) => (
                  <span class="text-muted">{formatTimestamp(event.timestamp)}</span>
                ),
              },
              {
                key: 'event',
                label: 'Event',
                render: (event) => (
                  <div class="min-w-0">
                    <span
                      class={`inline-flex items-center px-2 py-0.5 rounded-sm text-xs font-medium ${getAuditEventTypeBadgeClass(event.event)}`}
                    >
                      {event.event}
                    </span>
                    <div class="mt-1 truncate text-[11px] text-muted sm:hidden">
                      {event.success ? 'Success' : 'Failed'} · {event.user || 'Unknown user'} ·{' '}
                      {formatTimestamp(event.timestamp)}
                    </div>
                  </div>
                ),
              },
              {
                key: 'user',
                label: 'User',
                hiddenOnMobile: true,
                render: (event) => <span class="text-base-content">{event.user || '-'}</span>,
              },
              {
                key: 'ip',
                label: 'IP',
                hiddenOnMobile: true,
                render: (event) => (
                  <span class="text-muted font-mono text-xs">{event.ip || '-'}</span>
                ),
              },
              {
                key: 'details',
                label: 'Details',
                hiddenOnMobile: true,
                render: (event) => (
                  <span class="text-muted truncate max-w-xs" title={event.details || ''}>
                    {event.details || '-'}
                  </span>
                ),
              },
              {
                key: 'verification',
                label: 'Verification',
                render: (event) => {
                  if (!event.signature) {
                    return <span class="text-xs">Unsigned</span>;
                  }
                  const state = verification()[event.id];
                  const isVerifying = verifying()[event.id];
                  const badge = getAuditVerificationBadgePresentation(state);

                  return (
                    <div class="flex items-center gap-2">
                      <Show
                        when={isVerifying}
                        fallback={
                          <span
                            class={`inline-flex items-center px-2 py-0.5 rounded-sm text-xs font-medium ${badge.className}`}
                          >
                            {badge.label}
                          </span>
                        }
                      >
                        <span class="text-xs text-muted">Verifying…</span>
                      </Show>
                      <button
                        onClick={() => void verifyEvent(event)}
                        disabled={isVerifying}
                        class={AUDIT_VERIFY_ROW_BUTTON_CLASS}
                      >
                        Verify
                      </button>
                    </div>
                  );
                },
              },
            ]}
            keyExtractor={(event) => event.id}
            desktopMinWidth="900px"
          />
        </div>
      </Show>

      <Show when={!loading() && isPersistent() && filteredEvents().length === 0}>
        <EmptyState
          variant="panel"
          icon={
            activeFilterCount() > 0 ? <ShieldAlert class="h-5 w-5" /> : <Shield class="h-5 w-5" />
          }
          title={getAuditLogEmptyState(activeFilterCount()).title}
          description={getAuditLogEmptyState(activeFilterCount()).description}
          tone={activeFilterCount() > 0 ? 'info' : 'default'}
          actions={
            activeFilterCount() > 0 ? (
              <Button type="button" variant="info" size="mdCompact" onClick={clearFilters}>
                Clear all filters
              </Button>
            ) : undefined
          }
        />
      </Show>

      <Show when={!loading() && isPersistent()}>
        <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-end">
          <div class="flex items-center gap-2 text-xs text-muted">
            <label class="flex items-center gap-2">
              <span>Page</span>
              <input
                type="number"
                min="1"
                value={pageInput()}
                onInput={(e) => setPageInput(e.currentTarget.value)}
                onKeyDown={(e) => e.key === 'Enter' && submitPageInput()}
                class="min-h-10 sm:min-h-10 w-20 rounded-md border border-border bg-surface px-2.5 text-sm text-base-content"
              />
            </label>
            <button
              onClick={submitPageInput}
              class="min-h-10 sm:min-h-10 px-3 py-2.5 text-sm font-medium text-base-content bg-surface border border-border rounded-md hover:bg-surface-hover"
            >
              Go
            </button>
          </div>
          <div class="grid grid-cols-2 gap-2 sm:flex sm:flex-wrap sm:items-center sm:justify-end">
            <button
              onClick={goToFirstPage}
              disabled={pageNumber() === 1}
              class="min-h-10 sm:min-h-10 px-3 py-2.5 text-sm font-medium text-base-content bg-surface border border-border rounded-md hover:bg-surface-hover disabled:opacity-50"
            >
              First
            </button>
            <button
              onClick={goToPreviousPage}
              disabled={pageNumber() === 1}
              class="min-h-10 sm:min-h-10 px-3 py-2.5 text-sm font-medium text-base-content bg-surface border border-border rounded-md hover:bg-surface-hover disabled:opacity-50"
            >
              Previous
            </button>
            <button
              onClick={goToNextPage}
              disabled={!hasNextPage()}
              class="min-h-10 sm:min-h-10 px-3 py-2.5 text-sm font-medium text-base-content bg-surface border border-border rounded-md hover:bg-surface-hover disabled:opacity-50"
            >
              Next
            </button>
            <button
              onClick={goToLastPage}
              disabled={!hasNextPage()}
              class="min-h-10 sm:min-h-10 px-3 py-2.5 text-sm font-medium text-base-content bg-surface border border-border rounded-md hover:bg-surface-hover disabled:opacity-50"
            >
              Last
            </button>
          </div>
        </div>
      </Show>
    </SettingsPanel>
  );
}