Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(web): click-and-connect wizard for cloud connectors

Beenu Arora1bdf9303c583
diff --git a/apps/web/src/components/connectors/AddConnectorModal.tsx b/apps/web/src/components/connectors/AddConnectorModal.tsx
new file mode 100644
index 000000000..3d92a0746
--- /dev/null
+++ b/apps/web/src/components/connectors/AddConnectorModal.tsx
@@ -0,0 +1,658 @@
+'use client';
+
+/**
+ * Click-and-connect wizard for adding a new connector instance.
+ *
+ * Two-step flow:
+ *
+ * 1. **Catalog picker** — fetches ``GET /api/v1/connectors/catalog`` and
+ * renders one card per registered connector class, grouped by category.
+ * The catalog is the source of truth for which connectors this build
+ * supports; we never ship a hardcoded list in the frontend.
+ *
+ * 2. **Schema-driven config form** — each catalog entry declares its own
+ * ``fields[]`` (see ``BaseConnector.schema()``), so this component
+ * builds the form dynamically from the selected entry. Field types map
+ * to controls:
+ * - ``string`` / ``number`` → text/number input
+ * - ``secret`` → masked password input
+ * - ``textarea`` → multi-line input (used for pasted JSON keys)
+ * - ``select`` → native ``<select>`` with provided options
+ * - ``boolean`` → checkbox
+ *
+ * Test-before-save lives on the second screen: it POSTs the cleartext
+ * credentials to ``/api/v1/connectors/test`` (which forwards to the
+ * stateless connectors microservice) without persisting anything. Only on
+ * "Save" does the API encrypt the credentials in the vault and write a
+ * row to Postgres.
+ *
+ * The modal is intentionally a single component file because the wizard
+ * state machine is small (catalog → config → done) and splitting it would
+ * fragment the form/state coupling for no real reuse benefit.
+ */
+
+import { Fragment, useEffect, useMemo, useState } from 'react';
+import { AnimatePresence, motion } from 'framer-motion';
+import { clsx } from 'clsx';
+import toast from 'react-hot-toast';
+import {
+ connectorsApi,
+ type Connector,
+ type ConnectorCatalogEntry,
+ type ConnectorSchemaField,
+ type ConnectorTestResult,
+} from '@/lib/api';
+
+// ─── Field rendering helpers ────────────────────────────────────────────────
+
+/**
+ * Compute the initial form values for a catalog entry.
+ *
+ * Defaults from the schema flow into ``connector_config`` so the operator
+ * sees them already populated. Secrets always start empty — never seed a
+ * default secret, even if the schema were to declare one.
+ */
+function buildInitialValues(
+ fields: ConnectorSchemaField[],
+): Record<string, string | number | boolean> {
+ const values: Record<string, string | number | boolean> = {};
+ for (const f of fields) {
+ if (f.type === 'secret') {
+ values[f.name] = '';
+ continue;
+ }
+ if (f.default !== undefined && f.default !== null) {
+ values[f.name] = f.default as string | number | boolean;
+ continue;
+ }
+ if (f.type === 'boolean') {
+ values[f.name] = false;
+ continue;
+ }
+ if (f.type === 'number') {
+ values[f.name] = 0;
+ continue;
+ }
+ values[f.name] = '';
+ }
+ return values;
+}
+
+/**
+ * Split a flat values dict into ``auth_config`` (secrets) and
+ * ``connector_config`` (everything else).
+ *
+ * The backend expects this split because secrets get encrypted and
+ * non-secrets stay plaintext for poll-config readability in the UI.
+ */
+function partitionFormValues(
+ fields: ConnectorSchemaField[],
+ values: Record<string, string | number | boolean>,
+): { auth_config: Record<string, unknown>; connector_config: Record<string, unknown> } {
+ const auth_config: Record<string, unknown> = {};
+ const connector_config: Record<string, unknown> = {};
+ for (const f of fields) {
+ const v = values[f.name];
+ // Empty optional fields are omitted entirely so the backend doesn't
+ // need to disambiguate between "operator typed empty string" and
+ // "operator did not provide".
+ const isEmpty = v === '' || v === null || v === undefined;
+ if (isEmpty && !f.required) continue;
+ if (f.type === 'secret') {
+ auth_config[f.name] = v;
+ } else {
+ connector_config[f.name] = v;
+ }
+ }
+ return { auth_config, connector_config };
+}
+
+interface FieldInputProps {
+ field: ConnectorSchemaField;
+ value: string | number | boolean;
+ onChange: (next: string | number | boolean) => void;
+}
+
+function FieldInput({ field, value, onChange }: FieldInputProps) {
+ const baseClass =
+ 'w-full bg-gray-950/60 border border-gray-800 rounded-lg px-3 py-2 text-sm text-gray-100 placeholder-gray-600 focus:outline-none focus:border-blue-500/60 focus:ring-1 focus:ring-blue-500/30 transition-colors';
+
+ switch (field.type) {
+ case 'secret':
+ return (
+ <input
+ type="password"
+ autoComplete="new-password"
+ value={String(value ?? '')}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={field.placeholder ?? '••••••••'}
+ className={clsx(baseClass, 'font-mono')}
+ required={field.required}
+ />
+ );
+ case 'textarea':
+ return (
+ <textarea
+ value={String(value ?? '')}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={field.placeholder}
+ rows={6}
+ className={clsx(baseClass, 'font-mono text-xs resize-y min-h-[120px]')}
+ required={field.required}
+ />
+ );
+ case 'select':
+ return (
+ <select
+ value={String(value ?? '')}
+ onChange={(e) => onChange(e.target.value)}
+ className={baseClass}
+ required={field.required}
+ >
+ {!field.required && <option value="">— none —</option>}
+ {(field.options ?? []).map((opt) => (
+ <option key={opt.value} value={opt.value}>
+ {opt.label}
+ </option>
+ ))}
+ </select>
+ );
+ case 'boolean':
+ return (
+ <label className="flex items-center gap-2 cursor-pointer select-none">
+ <input
+ type="checkbox"
+ checked={Boolean(value)}
+ onChange={(e) => onChange(e.target.checked)}
+ className="h-4 w-4 rounded border-gray-700 bg-gray-900 text-blue-500 focus:ring-blue-500/30"
+ />
+ <span className="text-sm text-gray-300">{field.placeholder ?? 'Enabled'}</span>
+ </label>
+ );
+ case 'number':
+ return (
+ <input
+ type="number"
+ value={typeof value === 'number' ? value : Number(value ?? 0)}
+ onChange={(e) => {
+ const parsed = e.target.value === '' ? 0 : Number(e.target.value);
+ onChange(Number.isNaN(parsed) ? 0 : parsed);
+ }}
+ placeholder={field.placeholder}
+ className={baseClass}
+ required={field.required}
+ />
+ );
+ case 'string':
+ default:
+ return (
+ <input
+ type="text"
+ value={String(value ?? '')}
+ onChange={(e) => onChange(e.target.value)}
+ placeholder={field.placeholder}
+ className={baseClass}
+ required={field.required}
+ />
+ );
+ }
+}
+
+// ─── Catalog grid ────────────────────────────────────────────────────────────
+
+const CATEGORY_ORDER: string[] = [
+ 'edr',
+ 'siem',
+ 'cloud',
+ 'iam',
+ 'saas',
+ 'vcs',
+ 'network',
+];
+
+const CATEGORY_LABEL: Record<string, string> = {
+ edr: 'Endpoint',
+ siem: 'SIEM',
+ cloud: 'Cloud',
+ iam: 'Identity',
+ saas: 'SaaS',
+ vcs: 'Source Control',
+ network: 'Network',
+};
+
+function CatalogGrid({
+ entries,
+ onPick,
+}: {
+ entries: ConnectorCatalogEntry[];
+ onPick: (entry: ConnectorCatalogEntry) => void;
+}) {
+ const grouped = useMemo(() => {
+ const groups: Record<string, ConnectorCatalogEntry[]> = {};
+ for (const e of entries) {
+ const cat = e.category || 'other';
+ if (!groups[cat]) groups[cat] = [];
+ groups[cat].push(e);
+ }
+ // Stable sort by display order, with unknown categories appended.
+ const ordered = [...CATEGORY_ORDER.filter((c) => groups[c]), ...Object.keys(groups).filter((c) => !CATEGORY_ORDER.includes(c))];
+ return ordered.map((c) => ({ category: c, entries: groups[c] }));
+ }, [entries]);
+
+ if (entries.length === 0) {
+ return (
+ <div className="text-center text-sm text-gray-500 py-12">
+ No connector types are registered in this build.
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-6">
+ {grouped.map(({ category, entries: groupEntries }) => (
+ <section key={category} aria-labelledby={`cat-${category}`}>
+ <h3
+ id={`cat-${category}`}
+ className="text-[11px] uppercase tracking-wider text-gray-500 font-semibold mb-2"
+ >
+ {CATEGORY_LABEL[category] ?? category}
+ </h3>
+ <div className="grid grid-cols-2 lg:grid-cols-3 gap-3">
+ {groupEntries.map((entry) => (
+ <button
+ key={entry.connector_id}
+ type="button"
+ onClick={() => onPick(entry)}
+ className="text-left rounded-lg border border-gray-800/80 bg-gray-900/40 hover:bg-gray-900/80 hover:border-gray-700 transition-colors p-4 group"
+ >
+ <div className="flex items-start justify-between gap-2 mb-1">
+ <span className="text-sm font-medium text-gray-100 group-hover:text-white">
+ {entry.connector_name}
+ </span>
+ {entry.oauth?.supported_in_hosted && (
+ <span className="text-[10px] uppercase tracking-wider text-amber-300/80 bg-amber-500/10 border border-amber-500/20 rounded px-1.5 py-0.5">
+ OAuth soon
+ </span>
+ )}
+ </div>
+ <p className="text-xs text-gray-500 line-clamp-2">{entry.description}</p>
+ <p className="mt-2 text-[11px] text-gray-600 font-mono">{entry.connector_id}</p>
+ </button>
+ ))}
+ </div>
+ </section>
+ ))}
+ </div>
+ );
+}
+
+// ─── Config step ─────────────────────────────────────────────────────────────
+
+interface ConfigStepProps {
+ entry: ConnectorCatalogEntry;
+ values: Record<string, string | number | boolean>;
+ setValues: (next: Record<string, string | number | boolean>) => void;
+ instanceName: string;
+ setInstanceName: (next: string) => void;
+}
+
+function ConfigStep({
+ entry,
+ values,
+ setValues,
+ instanceName,
+ setInstanceName,
+}: ConfigStepProps) {
+ const updateField = (name: string, next: string | number | boolean) => {
+ setValues({ ...values, [name]: next });
+ };
+
+ return (
+ <div className="space-y-5">
+ {/* Friendly label for this instance — separate from the catalog name
+ so an operator can have e.g. two CrowdStrike tenants distinguished
+ by "Falcon — production" / "Falcon — staging". */}
+ <div>
+ <label className="block text-xs font-semibold text-gray-300 mb-1">
+ Instance name
+ <span className="text-red-400 ml-0.5">*</span>
+ </label>
+ <input
+ type="text"
+ value={instanceName}
+ onChange={(e) => setInstanceName(e.target.value)}
+ placeholder={`${entry.connector_name} — production`}
+ className="w-full bg-gray-950/60 border border-gray-800 rounded-lg px-3 py-2 text-sm text-gray-100 placeholder-gray-600 focus:outline-none focus:border-blue-500/60 focus:ring-1 focus:ring-blue-500/30"
+ required
+ />
+ <p className="mt-1 text-xs text-gray-500">
+ Shown in the connectors list and on alerts ingested through this connector.
+ </p>
+ </div>
+
+ {entry.fields.map((f) => (
+ <div key={f.name}>
+ <label className="block text-xs font-semibold text-gray-300 mb-1">
+ {f.label}
+ {f.required && <span className="text-red-400 ml-0.5">*</span>}
+ </label>
+ <FieldInput field={f} value={values[f.name]} onChange={(v) => updateField(f.name, v)} />
+ {f.help_text && (
+ <p className="mt-1 text-xs text-gray-500 leading-relaxed">{f.help_text}</p>
+ )}
+ </div>
+ ))}
+
+ {entry.docs_url && (
+ <p className="text-xs text-gray-500">
+ Need help?{' '}
+ <a
+ href={entry.docs_url}
+ target="_blank"
+ rel="noreferrer"
+ className="text-blue-400 hover:text-blue-300 underline-offset-2 hover:underline"
+ >
+ View setup guide
+ </a>
+ </p>
+ )}
+ </div>
+ );
+}
+
+// ─── Main modal ──────────────────────────────────────────────────────────────
+
+interface AddConnectorModalProps {
+ open: boolean;
+ onClose: () => void;
+ /** Called after a connector is created so the parent can refresh its list. */
+ onCreated?: (connector: Connector) => void;
+}
+
+type WizardStep = 'pick' | 'configure';
+
+export function AddConnectorModal({ open, onClose, onCreated }: AddConnectorModalProps) {
+ const [step, setStep] = useState<WizardStep>('pick');
+ const [catalog, setCatalog] = useState<ConnectorCatalogEntry[] | null>(null);
+ const [catalogError, setCatalogError] = useState<string | null>(null);
+
+ const [selected, setSelected] = useState<ConnectorCatalogEntry | null>(null);
+ const [values, setValues] = useState<Record<string, string | number | boolean>>({});
+ const [instanceName, setInstanceName] = useState<string>('');
+
+ const [testing, setTesting] = useState(false);
+ const [testResult, setTestResult] = useState<ConnectorTestResult | null>(null);
+ const [saving, setSaving] = useState(false);
+
+ // Load catalog whenever the modal opens. We don't keep stale data around
+ // between opens because the operator may have added a new connector class
+ // and redeployed.
+ useEffect(() => {
+ if (!open) return;
+ let cancelled = false;
+ setCatalog(null);
+ setCatalogError(null);
+ setStep('pick');
+ setSelected(null);
+ setValues({});
+ setInstanceName('');
+ setTestResult(null);
+
+ connectorsApi
+ .catalog()
+ .then((res) => {
+ if (cancelled) return;
+ setCatalog(res.connectors);
+ })
+ .catch((err: unknown) => {
+ if (cancelled) return;
+ const msg = err instanceof Error ? err.message : 'Failed to load connector catalog';
+ setCatalogError(msg);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [open]);
+
+ // Close on Escape — but only when we're on the picker. On the config
+ // screen, prefer the explicit Cancel button so a misclick doesn't lose
+ // the operator's typed credentials.
+ useEffect(() => {
+ if (!open) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape' && step === 'pick') {
+ onClose();
+ }
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [open, step, onClose]);
+
+ const handlePick = (entry: ConnectorCatalogEntry) => {
+ setSelected(entry);
+ setValues(buildInitialValues(entry.fields));
+ setInstanceName(entry.connector_name);
+ setTestResult(null);
+ setStep('configure');
+ };
+
+ const handleBack = () => {
+ setStep('pick');
+ setSelected(null);
+ setTestResult(null);
+ };
+
+ const handleTest = async () => {
+ if (!selected) return;
+ setTesting(true);
+ setTestResult(null);
+ try {
+ const { auth_config, connector_config } = partitionFormValues(selected.fields, values);
+ const result = await connectorsApi.testInline({
+ connector_type: selected.connector_id,
+ auth_config,
+ connector_config,
+ });
+ setTestResult(result);
+ if (result.success) {
+ toast.success('Connection test passed');
+ } else {
+ toast.error(result.error ?? result.message ?? 'Connection test failed');
+ }
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : 'Test request failed';
+ setTestResult({ success: false, error: msg });
+ toast.error(msg);
+ } finally {
+ setTesting(false);
+ }
+ };
+
+ const handleSave = async () => {
+ if (!selected) return;
+ if (!instanceName.trim()) {
+ toast.error('Please give this connector an instance name');
+ return;
+ }
+ setSaving(true);
+ try {
+ const { auth_config, connector_config } = partitionFormValues(selected.fields, values);
+ const created = await connectorsApi.create({
+ name: instanceName.trim(),
+ connector_type: selected.connector_id,
+ category: selected.category,
+ auth_config,
+ connector_config,
+ });
+ toast.success(`Connected ${created.name}`);
+ onCreated?.(created);
+ onClose();
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : 'Failed to save connector';
+ toast.error(msg);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <AnimatePresence>
+ {open && (
+ <Fragment>
+ {/* Backdrop */}
+ <motion.div
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ transition={{ duration: 0.15 }}
+ className="fixed inset-0 z-40 bg-black/60 backdrop-blur-sm"
+ onClick={() => {
+ if (step === 'pick') onClose();
+ }}
+ />
+
+ {/* Panel */}
+ <motion.div
+ initial={{ opacity: 0, y: 12, scale: 0.98 }}
+ animate={{ opacity: 1, y: 0, scale: 1 }}
+ exit={{ opacity: 0, y: 8, scale: 0.98 }}
+ transition={{ duration: 0.18, ease: 'easeOut' }}
+ className="fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none"
+ >
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="add-connector-title"
+ className="pointer-events-auto w-full max-w-3xl max-h-[85vh] overflow-hidden rounded-2xl border border-gray-800 bg-gray-950 shadow-2xl flex flex-col"
+ >
+ {/* Header */}
+ <div className="flex items-start justify-between gap-4 px-6 py-4 border-b border-gray-800">
+ <div>
+ <h2
+ id="add-connector-title"
+ className="text-base font-semibold text-gray-100"
+ >
+ {step === 'pick' ? 'Add connector' : `Configure ${selected?.connector_name ?? ''}`}
+ </h2>
+ <p className="text-xs text-gray-500 mt-0.5">
+ {step === 'pick'
+ ? 'Pick a security tool to connect. Credentials are encrypted with the AiSOC vault.'
+ : 'Credentials are tested against the upstream API and only saved on success.'}
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Close"
+ className="text-gray-500 hover:text-gray-300 transition-colors p-1"
+ >
+ <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
+ </svg>
+ </button>
+ </div>
+
+ {/* Body */}
+ <div className="flex-1 overflow-y-auto px-6 py-5">
+ {step === 'pick' &&
+ (catalog === null && !catalogError ? (
+ <div className="flex items-center justify-center h-32 text-gray-600">
+ <div className="animate-spin w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full" />
+ </div>
+ ) : catalogError ? (
+ <div className="text-sm text-red-300 bg-red-500/10 border border-red-500/20 rounded-lg p-4">
+ Failed to load connector catalog: {catalogError}
+ </div>
+ ) : (
+ <CatalogGrid entries={catalog ?? []} onPick={handlePick} />
+ ))}
+
+ {step === 'configure' && selected && (
+ <ConfigStep
+ entry={selected}
+ values={values}
+ setValues={setValues}
+ instanceName={instanceName}
+ setInstanceName={setInstanceName}
+ />
+ )}
+ </div>
+
+ {/* Footer */}
+ <div className="flex items-center justify-between gap-3 px-6 py-4 border-t border-gray-800 bg-gray-950/80">
+ {step === 'pick' ? (
+ <>
+ <p className="text-xs text-gray-600">
+ {(catalog?.length ?? 0)} connector type
+ {(catalog?.length ?? 0) === 1 ? '' : 's'} available
+ </p>
+ <button
+ type="button"
+ onClick={onClose}
+ className="text-sm text-gray-400 hover:text-gray-200 px-3 py-2 rounded-lg transition-colors"
+ >
+ Cancel
+ </button>
+ </>
+ ) : (
+ <>
+ <div className="flex items-center gap-2 min-w-0">
+ <button
+ type="button"
+ onClick={handleBack}
+ disabled={saving}
+ className="text-sm text-gray-400 hover:text-gray-200 px-3 py-2 rounded-lg transition-colors disabled:opacity-50"
+ >
+ ← Back
+ </button>
+ {testResult && (
+ <span
+ className={clsx(
+ 'truncate text-xs px-2 py-1 rounded-md border',
+ testResult.success
+ ? 'text-green-300 bg-green-500/10 border-green-500/20'
+ : 'text-red-300 bg-red-500/10 border-red-500/20',
+ )}
+ title={testResult.message ?? testResult.error ?? ''}
+ >
+ {testResult.success
+ ? testResult.message ?? 'Connection successful'
+ : testResult.error ?? testResult.message ?? 'Connection failed'}
+ </span>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={handleTest}
+ disabled={testing || saving}
+ className="text-sm bg-gray-800 hover:bg-gray-700 text-gray-200 px-3 py-2 rounded-lg transition-colors disabled:opacity-50 flex items-center gap-2"
+ >
+ {testing && (
+ <span className="animate-spin w-3.5 h-3.5 border-2 border-blue-400 border-t-transparent rounded-full" />
+ )}
+ Test connection
+ </button>
+ <button
+ type="button"
+ onClick={handleSave}
+ disabled={saving || testing}
+ className="text-sm bg-blue-600 hover:bg-blue-500 text-white px-4 py-2 rounded-lg transition-colors disabled:opacity-50 flex items-center gap-2"
+ >
+ {saving && (
+ <span className="animate-spin w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full" />
+ )}
+ Save connector
+ </button>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ </motion.div>
+ </Fragment>
+ )}
+ </AnimatePresence>
+ );
+}
diff --git a/apps/web/src/components/connectors/ConnectorInstanceList.tsx b/apps/web/src/components/connectors/ConnectorInstanceList.tsx
new file mode 100644
index 000000000..5ed091fe3
--- /dev/null
+++ b/apps/web/src/components/connectors/ConnectorInstanceList.tsx
@@ -0,0 +1,300 @@
+'use client';
+
+/**
+ * Grid of saved connector instances with per-card actions.
+ *
+ * The list itself is purely presentational — the parent (`ConnectorsView`)
+ * owns data fetching and mutation so SWR cache invalidation lives in one
+ * place. This component only knows how to render a `Connector[]` and emit
+ * action callbacks (test, delete) when the operator clicks a row.
+ *
+ * Layout follows the rest of the AiSOC dashboard: 3-up grid on wide
+ * screens, with a trailing "Add Connector" tile that the parent wires to
+ * the `AddConnectorModal`. Empty state replaces the grid entirely so a
+ * fresh tenant gets a useful onboarding nudge instead of just the
+ * dashed placeholder card.
+ */
+
+import { clsx } from 'clsx';
+import { EmptyState } from '@/components/ui/EmptyState';
+import { SkeletonCard } from '@/components/ui/Skeleton';
+import type { Connector } from '@/lib/api';
+
+const CONNECTOR_LABELS: Record<string, string> = {
+ crowdstrike: 'CS',
+ splunk: 'SPL',
+ aws_security_hub: 'AWS',
+ okta: 'OKT',
+ microsoft_sentinel: 'SNT',
+ azure_entra: 'AZE',
+ azure_activity: 'AZA',
+ azure_defender: 'AZD',
+ gcp_cloud_audit: 'GCP',
+ gcp_scc: 'SCC',
+ m365_audit: 'M365',
+ google_workspace: 'GWS',
+ cloudflare: 'CF',
+ github: 'GH',
+};
+
+const STATUS_CONFIG: Record<
+ Connector['status'],
+ { label: string; color: string; dot: string }
+> = {
+ active: {
+ label: 'Active',
+ color: 'text-green-400 bg-green-500/10 border-green-500/20',
+ dot: 'bg-green-400',
+ },
+ inactive: {
+ label: 'Inactive',
+ color: 'text-gray-400 bg-gray-500/10 border-gray-500/20',
+ dot: 'bg-gray-500',
+ },
+ error: {
+ label: 'Error',
+ color: 'text-red-400 bg-red-500/10 border-red-500/20',
+ dot: 'bg-red-400',
+ },
+ configuring: {
+ label: 'Configuring',
+ color: 'text-amber-300 bg-amber-500/10 border-amber-500/20',
+ dot: 'bg-amber-400',
+ },
+};
+
+function formatLastSync(ts?: string): string {
+ if (!ts) return 'never';
+ const diff = Date.now() - new Date(ts).getTime();
+ if (Number.isNaN(diff)) return 'never';
+ const mins = Math.floor(diff / 60000);
+ if (mins < 1) return 'just now';
+ if (mins < 60) return `${mins}m ago`;
+ const hrs = Math.floor(mins / 60);
+ if (hrs < 24) return `${hrs}h ago`;
+ return `${Math.floor(hrs / 24)}d ago`;
+}
+
+function abbreviateType(type: string): string {
+ if (CONNECTOR_LABELS[type]) return CONNECTOR_LABELS[type];
+ // Fall back to the first 3 letters of the connector type so unknown
+ // connectors still get a readable badge instead of "GEN".
+ return type.slice(0, 3).toUpperCase();
+}
+
+// ─── Card ────────────────────────────────────────────────────────────────────
+
+interface ConnectorCardProps {
+ connector: Connector;
+ testing: boolean;
+ /** `true` = last test passed, `false` = failed, `undefined` = idle. */
+ testResult: boolean | undefined;
+ onTest: (id: string) => void;
+ onConfigure?: (connector: Connector) => void;
+ onDelete?: (connector: Connector) => void;
+}
+
+function ConnectorCard({
+ connector,
+ testing,
+ testResult,
+ onTest,
+ onConfigure,
+ onDelete,
+}: ConnectorCardProps) {
+ const statusCfg = STATUS_CONFIG[connector.status] ?? STATUS_CONFIG.configuring;
+ const alertCount = connector.alertCount ?? connector.alertsIngested ?? 0;
+
+ return (
+ <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-5 hover:border-gray-700/60 transition-colors flex flex-col">
+ <div className="flex items-start justify-between mb-3">
+ <div className="flex items-center gap-3 min-w-0">
+ <div className="w-10 h-10 bg-gray-800 rounded-xl flex items-center justify-center text-[10px] font-semibold uppercase tracking-wider text-gray-400 flex-shrink-0">
+ {abbreviateType(connector.type)}
+ </div>
+ <div className="min-w-0">
+ <h3 className="text-sm font-medium text-gray-200 truncate">{connector.name}</h3>
+ <p className="text-xs text-gray-500 truncate">{connector.type}</p>
+ </div>
+ </div>
+ <span
+ className={clsx(
+ 'text-xs px-2 py-0.5 rounded-full border flex items-center gap-1 flex-shrink-0',
+ statusCfg.color,
+ )}
+ title={connector.errorMessage}
+ >
+ <span className={clsx('w-1.5 h-1.5 rounded-full', statusCfg.dot)} />
+ {statusCfg.label}
+ </span>
+ </div>
+
+ {connector.description && (
+ <p className="text-xs text-gray-500 mb-4 line-clamp-2">{connector.description}</p>
+ )}
+
+ <div className="grid grid-cols-2 gap-2 mb-4">
+ <div className="bg-gray-800/60 rounded-lg p-2">
+ <p className="text-xs text-gray-500">Events ingested</p>
+ <p className="text-sm font-medium text-gray-300">
+ {alertCount.toLocaleString()}
+ </p>
+ </div>
+ <div className="bg-gray-800/60 rounded-lg p-2">
+ <p className="text-xs text-gray-500">Last sync</p>
+ <p className="text-sm font-medium text-gray-300">
+ {formatLastSync(connector.lastSync)}
+ </p>
+ </div>
+ </div>
+
+ <div className="mt-auto flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => onTest(connector.id)}
+ disabled={testing}
+ className="flex-1 text-xs bg-gray-800 hover:bg-gray-700 text-gray-300 px-3 py-2 rounded-lg transition-colors disabled:opacity-60 flex items-center justify-center gap-2"
+ >
+ {testing && (
+ <span className="animate-spin w-3 h-3 border-2 border-blue-400 border-t-transparent rounded-full" />
+ )}
+ Test
+ </button>
+ <button
+ type="button"
+ onClick={() => onConfigure?.(connector)}
+ className="flex-1 text-xs bg-blue-600/20 hover:bg-blue-600/30 text-blue-400 px-3 py-2 rounded-lg transition-colors border border-blue-500/20"
+ >
+ Configure
+ </button>
+ {onDelete && (
+ <button
+ type="button"
+ onClick={() => onDelete(connector)}
+ aria-label={`Delete ${connector.name}`}
+ className="text-xs text-gray-500 hover:text-red-400 px-2 py-2 rounded-lg transition-colors"
+ >
+ <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={1.8}
+ d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6M1 7h22M9 7V4a1 1 0 011-1h4a1 1 0 011 1v3"
+ />
+ </svg>
+ </button>
+ )}
+ </div>
+
+ {testResult !== undefined && (
+ <p
+ className={clsx(
+ 'mt-3 text-xs',
+ testResult ? 'text-green-400' : 'text-red-400',
+ )}
+ >
+ {testResult ? '✓ Connection successful' : '✗ Connection failed'}
+ </p>
+ )}
+ </div>
+ );
+}
+
+// ─── List ────────────────────────────────────────────────────────────────────
+
+export interface ConnectorInstanceListProps {
+ connectors: Connector[];
+ isLoading?: boolean;
+ testingId?: string | null;
+ testResults?: Record<string, boolean | undefined>;
+ onTest: (id: string) => void;
+ onAdd: () => void;
+ onConfigure?: (connector: Connector) => void;
+ onDelete?: (connector: Connector) => void;
+}
+
+export function ConnectorInstanceList({
+ connectors,
+ isLoading,
+ testingId,
+ testResults,
+ onTest,
+ onAdd,
+ onConfigure,
+ onDelete,
+}: ConnectorInstanceListProps) {
+ if (isLoading) {
+ return (
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
+ <SkeletonCard />
+ <SkeletonCard />
+ <SkeletonCard />
+ </div>
+ );
+ }
+
+ if (connectors.length === 0) {
+ return (
+ <EmptyState
+ icon={
+ <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={1.5}
+ d="M13.5 21v-7.5a.75.75 0 01.75-.75h3a.75.75 0 01.75.75V21m-4.5 0H2.36m11.14 0H18m0 0h3.64m-1.39 0V9.349m-16.5 11.65V9.35m0 0a3.001 3.001 0 003.75-.615A2.993 2.993 0 009.75 9.75c.896 0 1.7-.393 2.25-1.016a2.993 2.993 0 002.25 1.016c.896 0 1.7-.393 2.25-1.016a3.001 3.001 0 003.75.614m-16.5 0a3.004 3.004 0 01-.621-4.72L4.318 3.44A1.5 1.5 0 015.378 3h13.243a1.5 1.5 0 011.06.44l1.19 1.189a3 3 0 01-.621 4.72m-13.5 8.65h3.75a.75.75 0 00.75-.75V13.5a.75.75 0 00-.75-.75H6.75a.75.75 0 00-.75.75v3.75c0 .415.336.75.75.75z"
+ />
+ </svg>
+ }
+ title="No connectors yet"
+ description="Connect your first security tool to start ingesting alerts. Credentials are encrypted at rest with the AiSOC vault."
+ action={
+ <button
+ type="button"
+ onClick={onAdd}
+ className="bg-blue-600 hover:bg-blue-500 text-white text-sm px-4 py-2 rounded-lg transition-colors flex items-center gap-2"
+ >
+ <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
+ </svg>
+ Add your first connector
+ </button>
+ }
+ />
+ );
+ }
+
+ return (
+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
+ {connectors.map((connector) => (
+ <ConnectorCard
+ key={connector.id}
+ connector={connector}
+ testing={testingId === connector.id}
+ testResult={testResults?.[connector.id]}
+ onTest={onTest}
+ onConfigure={onConfigure}
+ onDelete={onDelete}
+ />
+ ))}
+
+ {/* Trailing "add new" tile so adding a second/third connector is one
+ click without having to scroll back to the page header. */}
+ <button
+ type="button"
+ onClick={onAdd}
+ className="bg-gray-900/30 border border-dashed border-gray-700/60 rounded-xl p-5 flex flex-col items-center justify-center gap-3 hover:border-gray-600/60 hover:bg-gray-900/50 transition-colors text-left"
+ >
+ <div className="w-10 h-10 bg-gray-800/60 rounded-xl flex items-center justify-center text-gray-500">
+ <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
+ </svg>
+ </div>
+ <div className="text-center">
+ <p className="text-sm text-gray-300">Add Connector</p>
+ <p className="text-xs text-gray-600 mt-0.5">Connect a new security tool</p>
+ </div>
+ </button>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/connectors/ConnectorsView.tsx b/apps/web/src/components/connectors/ConnectorsView.tsx
index f1e9dd5a0..8bccd0fc1 100644
--- a/apps/web/src/components/connectors/ConnectorsView.tsx
+++ b/apps/web/src/components/connectors/ConnectorsView.tsx
@@ -1,176 +1,108 @@
'use client';
-import { useState } from 'react';
+/**
+ * Top-level Connectors page.
+ *
+ * Owns the SWR cache for `connectorsApi.list()` and renders three sub-views
+ * depending on state:
+ *
+ * - loading → skeleton tiles
+ * - error → `ErrorState` with retry
+ * - data → header stats + `ConnectorInstanceList` + add-connector modal
+ *
+ * Mock data is intentionally gone — the modal can spin up real instances
+ * against the backend, so dogfooding the empty state is now both more
+ * informative and one click from being populated.
+ */
+
+import { useMemo, useState } from 'react';
import useSWR from 'swr';
-import { connectorsApi, type Connector } from '@/lib/api';
+import toast from 'react-hot-toast';
import { clsx } from 'clsx';
-// ─── Mock Data ────────────────────────────────────────────────────────────────
-
-const MOCK_CONNECTORS: Connector[] = [
- {
- id: 'conn-crowdstrike',
- name: 'CrowdStrike Falcon',
- type: 'crowdstrike',
- status: 'active',
- enabled: true,
- lastSync: new Date(Date.now() - 300000).toISOString(),
- alertCount: 1247,
- config: { baseUrl: 'https://api.crowdstrike.com', clientId: 'abc123' },
- description: 'CrowdStrike Falcon endpoint detection and response',
- },
- {
- id: 'conn-splunk',
- name: 'Splunk SIEM',
- type: 'splunk',
- status: 'active',
- enabled: true,
- lastSync: new Date(Date.now() - 600000).toISOString(),
- alertCount: 3891,
- config: { host: 'splunk.internal', port: 8089 },
- description: 'Splunk Enterprise SIEM correlation search alerts',
- },
- {
- id: 'conn-aws',
- name: 'AWS Security Hub',
- type: 'aws',
- status: 'active',
- enabled: true,
- lastSync: new Date(Date.now() - 120000).toISOString(),
- alertCount: 562,
- config: { region: 'us-east-1', accountId: '123456789012' },
- description: 'AWS Security Hub findings from GuardDuty, Inspector, and Macie',
- },
- {
- id: 'conn-okta',
- name: 'Okta Identity',
- type: 'okta',
- status: 'error',
- enabled: true,
- lastSync: new Date(Date.now() - 7200000).toISOString(),
- alertCount: 89,
- config: { domain: 'company.okta.com' },
- description: 'Okta identity provider suspicious sign-in events',
- },
- {
- id: 'conn-sentinel',
- name: 'Microsoft Sentinel',
- type: 'sentinel',
- status: 'inactive',
- enabled: false,
- lastSync: new Date(Date.now() - 86400000).toISOString(),
- alertCount: 0,
- config: { workspaceId: 'ws-abc-123', subscriptionId: 'sub-xyz-456' },
- description: 'Microsoft Sentinel cloud-native SIEM',
- },
-];
-
-const CONNECTOR_LABELS: Record<string, string> = {
- crowdstrike: 'CS',
- splunk: 'SPL',
- aws: 'AWS',
- okta: 'OKT',
- sentinel: 'SNT',
- custom: 'GEN',
-};
-
-const STATUS_CONFIG = {
- active: { label: 'Active', color: 'text-green-400 bg-green-500/10 border-green-500/20', dot: 'bg-green-400' },
- inactive: { label: 'Inactive', color: 'text-gray-400 bg-gray-500/10 border-gray-500/20', dot: 'bg-gray-500' },
- error: { label: 'Error', color: 'text-red-400 bg-red-500/10 border-red-500/20', dot: 'bg-red-400' },
-};
-
-function formatLastSync(ts: string) {
- const diff = Date.now() - new Date(ts).getTime();
- const mins = Math.floor(diff / 60000);
- if (mins < 1) return 'just now';
- if (mins < 60) return `${mins}m ago`;
- const hrs = Math.floor(mins / 60);
- if (hrs < 24) return `${hrs}h ago`;
- return `${Math.floor(hrs / 24)}d ago`;
-}
-
-// ─── Connector Card ───────────────────────────────────────────────────────────
-
-function ConnectorCard({ connector, onTest }: { connector: Connector; onTest: (id: string) => void }) {
- const statusCfg = STATUS_CONFIG[connector.status];
-
- return (
- <div className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-5 hover:border-gray-700/60 transition-colors">
- <div className="flex items-start justify-between mb-3">
- <div className="flex items-center gap-3">
- <div className="w-10 h-10 bg-gray-800 rounded-xl flex items-center justify-center text-[10px] font-semibold uppercase tracking-wider text-gray-400">
- {CONNECTOR_LABELS[connector.type] ?? 'GEN'}
- </div>
- <div>
- <h3 className="text-sm font-medium text-gray-200">{connector.name}</h3>
- <p className="text-xs text-gray-500 capitalize">{connector.type}</p>
- </div>
- </div>
- <span className={clsx('text-xs px-2 py-0.5 rounded-full border flex items-center gap-1', statusCfg.color)}>
- <span className={clsx('w-1.5 h-1.5 rounded-full', statusCfg.dot)} />
- {statusCfg.label}
- </span>
- </div>
-
- <p className="text-xs text-gray-500 mb-4">{connector.description}</p>
-
- <div className="grid grid-cols-2 gap-2 mb-4">
- <div className="bg-gray-800/60 rounded-lg p-2">
- <p className="text-xs text-gray-500">Alerts fetched</p>
- <p className="text-sm font-medium text-gray-300">{connector.alertCount.toLocaleString()}</p>
- </div>
- <div className="bg-gray-800/60 rounded-lg p-2">
- <p className="text-xs text-gray-500">Last sync</p>
- <p className="text-sm font-medium text-gray-300">{formatLastSync(connector.lastSync)}</p>
- </div>
- </div>
-
- <div className="flex items-center gap-2">
- <button
- onClick={() => onTest(connector.id)}
- className="flex-1 text-xs bg-gray-800 hover:bg-gray-700 text-gray-300 px-3 py-2 rounded-lg transition-colors"
- >
- Test Connection
- </button>
- <button className="flex-1 text-xs bg-blue-600/20 hover:bg-blue-600/30 text-blue-400 px-3 py-2 rounded-lg transition-colors border border-blue-500/20">
- Configure
- </button>
- </div>
- </div>
- );
-}
-
-// ─── Main View ────────────────────────────────────────────────────────────────
+import { connectorsApi, type Connector } from '@/lib/api';
+import { ErrorState } from '@/components/ui/ErrorState';
+import { AddConnectorModal } from './AddConnectorModal';
+import { ConnectorInstanceList } from './ConnectorInstanceList';
export function ConnectorsView() {
+ const [modalOpen, setModalOpen] = useState(false);
const [testingId, setTestingId] = useState<string | null>(null);
- const [testResults, setTestResults] = useState<Record<string, boolean | null>>({});
+ const [testResults, setTestResults] = useState<Record<string, boolean | undefined>>({});
- const { data: connData, isLoading } = useSWR(
+ const { data, error, isLoading, mutate } = useSWR(
'connectors',
() => connectorsApi.list(),
- { fallbackData: { connectors: MOCK_CONNECTORS, total: MOCK_CONNECTORS.length } }
+ { revalidateOnFocus: false },
);
- const connectors = connData?.connectors || MOCK_CONNECTORS;
+ const connectors: Connector[] = useMemo(() => data?.connectors ?? [], [data]);
+
+ const stats = useMemo(() => {
+ const active = connectors.filter((c) => c.status === 'active').length;
+ const errored = connectors.filter((c) => c.status === 'error').length;
+ const totalEvents = connectors.reduce(
+ (sum, c) => sum + (c.alertCount ?? c.alertsIngested ?? 0),
+ 0,
+ );
+ return { active, errored, totalEvents };
+ }, [connectors]);
+
+ // ─── Actions ──────────────────────────────────────────────────────────────
const handleTest = async (id: string) => {
setTestingId(id);
- setTestResults(prev => ({ ...prev, [id]: null }));
+ setTestResults((prev) => ({ ...prev, [id]: undefined }));
try {
const result = await connectorsApi.test(id);
- setTestResults(prev => ({ ...prev, [id]: result.success }));
- } catch {
- setTestResults(prev => ({ ...prev, [id]: false }));
+ setTestResults((prev) => ({ ...prev, [id]: result.success }));
+ if (result.success) {
+ toast.success(result.message ?? 'Connection test passed');
+ } else {
+ toast.error(result.error ?? result.message ?? 'Connection test failed');
+ }
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : 'Test request failed';
+ setTestResults((prev) => ({ ...prev, [id]: false }));
+ toast.error(msg);
} finally {
setTestingId(null);
}
};
- const activeCount = connectors.filter(c => c.status === 'active').length;
- const errorCount = connectors.filter(c => c.status === 'error').length;
- const totalAlerts = connectors.reduce((sum, c) => sum + c.alertCount, 0);
+ const handleDelete = async (connector: Connector) => {
+ // Browser confirm is intentional — destructive, infrequent, and we don't
+ // yet have a shared confirmation dialog component. Worth revisiting once
+ // we add one to `components/ui/`.
+ const ok = window.confirm(
+ `Delete connector "${connector.name}"? This stops polling and removes its credentials. Already-ingested alerts are preserved.`,
+ );
+ if (!ok) return;
+
+ try {
+ await connectorsApi.delete(connector.id);
+ toast.success(`Removed ${connector.name}`);
+ mutate();
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : 'Failed to delete connector';
+ toast.error(msg);
+ }
+ };
+
+ const handleConfigure = (_connector: Connector) => {
+ // Inline edit dialog ships in a follow-up. For now, surface a hint so
+ // operators don't think the button is broken — the modal already covers
+ // create + test, which is the high-value path for v1.
+ toast('Connector editing UI is coming soon. Delete + re-add for now.', {
+ icon: '🔧',
+ });
+ };
+
+ const handleCreated = () => {
+ mutate();
+ };
+
+ // ─── Render ───────────────────────────────────────────────────────────────
return (
<div className="space-y-5">
@@ -182,7 +114,11 @@ export function ConnectorsView() {
Security tool integrations and data source management
</p>
</div>
- <button className="bg-blue-600 hover:bg-blue-500 text-white text-sm px-4 py-2 rounded-lg transition-colors flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => setModalOpen(true)}
+ className="bg-blue-600 hover:bg-blue-500 text-white text-sm px-4 py-2 rounded-lg transition-colors flex items-center gap-2"
+ >
<svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
</svg>
@@ -190,75 +126,56 @@ export function ConnectorsView() {
</button>
</div>
- {/* Stats */}
- <div className="grid grid-cols-4 gap-3">
+ {/* Stats — render even with zero connectors so the layout is stable
+ between empty/populated states. */}
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
{[
{ label: 'Total Connectors', value: connectors.length, color: 'text-blue-400' },
- { label: 'Active', value: activeCount, color: 'text-green-400' },
- { label: 'Errors', value: errorCount, color: 'text-red-400' },
- { label: 'Total Alerts', value: totalAlerts.toLocaleString(), color: 'text-purple-400' },
+ { label: 'Active', value: stats.active, color: 'text-green-400' },
+ { label: 'Errors', value: stats.errored, color: 'text-red-400' },
+ {
+ label: 'Events Ingested',
+ value: stats.totalEvents.toLocaleString(),
+ color: 'text-purple-400',
+ },
].map((stat) => (
- <div key={stat.label} className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-4">
+ <div
+ key={stat.label}
+ className="bg-gray-900/60 border border-gray-800/60 rounded-xl p-4"
+ >
<p className={clsx('text-2xl font-bold mb-1', stat.color)}>{stat.value}</p>
<p className="text-xs text-gray-500">{stat.label}</p>
</div>
))}
</div>
- {/* Connector Grid */}
- {isLoading ? (
- <div className="flex items-center justify-center h-32 text-gray-600">
- <div className="animate-spin w-6 h-6 border-2 border-blue-500 border-t-transparent rounded-full" />
- </div>
+ {/* Body */}
+ {error ? (
+ <ErrorState
+ title="Could not load connectors"
+ description="The API returned an error while fetching your connector instances. The connectors service may still be starting up."
+ error={error}
+ onRetry={() => mutate()}
+ />
) : (
- <div className="grid grid-cols-3 gap-4">
- {connectors.map((connector) => (
- <ConnectorCard
- key={connector.id}
- connector={connector}
- onTest={handleTest}
- />
- ))}
-
- {/* Add New Card */}
- <div className="bg-gray-900/30 border border-dashed border-gray-700/60 rounded-xl p-5 flex flex-col items-center justify-center gap-3 hover:border-gray-600/60 transition-colors cursor-pointer">
- <div className="w-10 h-10 bg-gray-800/60 rounded-xl flex items-center justify-center text-gray-500">
- <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
- </svg>
- </div>
- <div className="text-center">
- <p className="text-sm text-gray-500">Add Connector</p>
- <p className="text-xs text-gray-600 mt-0.5">Connect a new security tool</p>
- </div>
- </div>
- </div>
+ <ConnectorInstanceList
+ connectors={connectors}
+ isLoading={isLoading && !data}
+ testingId={testingId}
+ testResults={testResults}
+ onTest={handleTest}
+ onAdd={() => setModalOpen(true)}
+ onConfigure={handleConfigure}
+ onDelete={handleDelete}
+ />
)}
- {/* Test Results Notifications */}
- {Object.entries(testResults).filter(([, v]) => v !== null).length > 0 && (
- <div className="space-y-2">
- {Object.entries(testResults).map(([id, success]) => {
- if (success === null) return null;
- const conn = connectors.find(c => c.id === id);
- if (!conn) return null;
- return (
- <div
- key={id}
- className={clsx(
- 'text-sm px-4 py-2 rounded-lg border flex items-center gap-2',
- success
- ? 'text-green-400 bg-green-500/10 border-green-500/20'
- : 'text-red-400 bg-red-500/10 border-red-500/20'
- )}
- >
- <span className="text-[10px] font-semibold uppercase tracking-wider">{success ? 'ok' : 'fail'}</span>
- <span>{conn.name}: {success ? 'Connection successful' : 'Connection failed'}</span>
- </div>
- );
- })}
- </div>
- )}
+ {/* Add modal */}
+ <AddConnectorModal
+ open={modalOpen}
+ onClose={() => setModalOpen(false)}
+ onCreated={handleCreated}
+ />
</div>
);
}
diff --git a/apps/web/src/components/settings/SettingsView.tsx b/apps/web/src/components/settings/SettingsView.tsx
index ae794c9fe..008b90d5b 100644
--- a/apps/web/src/components/settings/SettingsView.tsx
+++ b/apps/web/src/components/settings/SettingsView.tsx
@@ -724,7 +724,7 @@ function IntegrationsPanel() {
);
try {
if (!useFallback) {
- await connectorsApi.update(connector.id, { enabled: next });
+ await connectorsApi.update(connector.id, { is_enabled: next });
}
toast.success(next ? 'Connector enabled' : 'Connector disabled');
mutate();
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 8581d1537..1f9d4bdf9 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -581,6 +581,7 @@ export interface Connector {
/** `true` when the connector is enabled (separate from runtime status). */
enabled?: boolean;
tenantId?: string;
+ category?: string;
config?: Record<string, unknown>;
lastSync?: string;
/** Number of alerts ingested through this connector. */
@@ -597,28 +598,195 @@ export interface ConnectorsResponse {
total: number;
}
+/** A single config field surfaced by ``BaseConnector.schema()`` on the backend. */
+export interface ConnectorSchemaField {
+ name: string;
+ type: 'string' | 'secret' | 'select' | 'textarea' | 'boolean' | 'number';
+ label: string;
+ required?: boolean;
+ default?: string | number | boolean | null;
+ placeholder?: string;
+ help_text?: string;
+ options?: Array<{ value: string; label: string }>;
+}
+
+/** Forward-looking OAuth hints; rendered as "Hosted OAuth coming soon". */
+export interface ConnectorOAuthHints {
+ supported_in_hosted?: boolean;
+ authorize_url?: string;
+ token_url?: string;
+ scopes?: string[];
+}
+
+/** A catalog entry: one available connector type with its config schema. */
+export interface ConnectorCatalogEntry {
+ connector_id: string;
+ connector_name: string;
+ category: string;
+ description: string;
+ fields: ConnectorSchemaField[];
+ docs_url?: string;
+ oauth?: ConnectorOAuthHints;
+}
+
+export interface ConnectorCatalogResponse {
+ connectors: ConnectorCatalogEntry[];
+}
+
+/** Result of a "Test connection" call (pre-save or against a saved instance). */
+export interface ConnectorTestResult {
+ success: boolean;
+ message?: string;
+ error?: string;
+ latency_ms?: number;
+ latencyMs?: number;
+ details?: Record<string, unknown>;
+}
+
+/** Raw shape returned by the API for a connector instance row. */
+interface BackendConnectorResponse {
+ id: string;
+ tenant_id: string;
+ name: string;
+ connector_type: string;
+ category: string;
+ is_enabled: boolean;
+ connector_config: Record<string, unknown>;
+ health_status: string;
+ last_health_check: string | null;
+ last_sync: string | null;
+ events_ingested: number;
+ error_count: number;
+ tags: string[];
+ created_at: string;
+ updated_at: string;
+}
+
+/**
+ * Map the backend ``health_status`` enum (``healthy``/``unhealthy``/``unknown``)
+ * to the frontend ``ConnectorStatus`` (``active``/``inactive``/``error``/
+ * ``configuring``). The mapping also folds in ``is_enabled`` because a disabled
+ * connector should always render as ``inactive`` in the UI regardless of its
+ * last health check.
+ */
+function deriveConnectorStatus(row: BackendConnectorResponse): ConnectorStatus {
+ if (!row.is_enabled) return 'inactive';
+ switch (row.health_status) {
+ case 'healthy':
+ return 'active';
+ case 'unhealthy':
+ case 'error':
+ return 'error';
+ case 'unknown':
+ case '':
+ return 'configuring';
+ default:
+ return 'configuring';
+ }
+}
+
+function mapBackendConnector(row: BackendConnectorResponse): Connector {
+ return {
+ id: row.id,
+ name: row.name,
+ type: row.connector_type,
+ category: row.category,
+ status: deriveConnectorStatus(row),
+ enabled: row.is_enabled,
+ tenantId: row.tenant_id,
+ config: row.connector_config,
+ lastSync: row.last_sync ?? undefined,
+ alertCount: row.events_ingested,
+ alertsIngested: row.events_ingested,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ };
+}
+
+export interface CreateConnectorPayload {
+ name: string;
+ connector_type: string;
+ category?: string;
+ auth_config?: Record<string, unknown>;
+ connector_config?: Record<string, unknown>;
+ tags?: string[];
+}
+
+export interface UpdateConnectorPayload {
+ name?: string;
+ is_enabled?: boolean;
+ auth_config?: Record<string, unknown>;
+ connector_config?: Record<string, unknown>;
+ tags?: string[];
+}
+
+export interface TestConnectorPayload {
+ connector_type: string;
+ auth_config?: Record<string, unknown>;
+ connector_config?: Record<string, unknown>;
+}
+
export const connectorsApi = {
- list: () => request<ConnectorsResponse>('/api/v1/connectors'),
+ /**
+ * List connector instances for the current tenant.
+ *
+ * The backend returns a raw ``list[ConnectorResponse]``; we wrap it in a
+ * ``ConnectorsResponse`` envelope and map each row from snake_case to the
+ * camelCase frontend shape so views never have to reach into raw API rows.
+ */
+ list: async (): Promise<ConnectorsResponse> => {
+ const rows = await request<BackendConnectorResponse[]>(
+ '/api/v1/connectors',
+ );
+ const connectors = rows.map(mapBackendConnector);
+ return { connectors, total: connectors.length };
+ },
- get: (id: string) => request<Connector>(`/api/v1/connectors/${id}`),
+ /** Catalog of available connector types (one entry per registered class). */
+ catalog: () =>
+ request<ConnectorCatalogResponse>('/api/v1/connectors/catalog'),
- create: (data: Partial<Connector>) =>
- request<Connector>('/api/v1/connectors', {
+ get: async (id: string): Promise<Connector> => {
+ const row = await request<BackendConnectorResponse>(
+ `/api/v1/connectors/${id}`,
+ );
+ return mapBackendConnector(row);
+ },
+
+ create: async (data: CreateConnectorPayload): Promise<Connector> => {
+ const row = await request<BackendConnectorResponse>('/api/v1/connectors', {
method: 'POST',
body: JSON.stringify(data),
- }),
+ });
+ return mapBackendConnector(row);
+ },
- update: (id: string, data: Partial<Connector>) =>
- request<Connector>(`/api/v1/connectors/${id}`, {
- method: 'PATCH',
- body: JSON.stringify(data),
- }),
+ update: async (
+ id: string,
+ data: UpdateConnectorPayload,
+ ): Promise<Connector> => {
+ const row = await request<BackendConnectorResponse>(
+ `/api/v1/connectors/${id}`,
+ {
+ method: 'PATCH',
+ body: JSON.stringify(data),
+ },
+ );
+ return mapBackendConnector(row);
+ },
+ /** Run "Test connection" against a saved instance. */
test: (id: string) =>
- request<{ success: boolean; message: string; latencyMs: number }>(
- `/api/v1/connectors/${id}/test`,
- { method: 'POST' },
- ),
+ request<ConnectorTestResult>(`/api/v1/connectors/${id}/test`, {
+ method: 'POST',
+ }),
+
+ /** Run "Test connection" with un-saved credentials from the wizard. */
+ testInline: (payload: TestConnectorPayload) =>
+ request<ConnectorTestResult>('/api/v1/connectors/test', {
+ method: 'POST',
+ body: JSON.stringify(payload),
+ }),
delete: (id: string) =>
request<void>(`/api/v1/connectors/${id}`, { method: 'DELETE' }),