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.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(web): WS-C2 — playbook gallery with one-click fork + DAG preview
Beenu Arorabd8f43b69c99
diff --git a/apps/web/src/components/playbooks/DAGPreviewDrawer.tsx b/apps/web/src/components/playbooks/DAGPreviewDrawer.tsxnew file mode 100644index 000000000..8922e70d8--- /dev/null+++ b/apps/web/src/components/playbooks/DAGPreviewDrawer.tsx@@ -0,0 +1,174 @@+'use client';++/**+ * DAGPreviewDrawer+ * ================+ * Right-side overlay drawer that renders a read-only DAG preview of a+ * playbook (used by the gallery for one-click "Preview" before forking+ * or editing). The PlaybookFlowCanvas pulls in @xyflow/react which is a+ * sizable dependency, so we lazy-load it here to keep the gallery's+ * initial bundle small.+ *+ * Props:+ * playbook – playbook to preview (null = drawer closed)+ * onClose – fires when the user dismisses the drawer+ * onEdit – optional handler for the "Edit" CTA (falls back to a+ * <Link> to /playbooks/<id> when omitted)+ * onFork – optional handler for the "Fork" CTA (only shown when+ * provided, e.g. for shipped packs)+ * forking – when true, disables the Fork CTA and shows a spinner+ */++import React, { Suspense, lazy, useEffect } from 'react';+import Link from 'next/link';+import type { Playbook } from './types';+import { isShippedPack, categoryOf, categoryLabel, categoryBadgeClass } from './packHelpers';++// Lazy-load the React Flow canvas — it pulls in @xyflow/react and+// playbook-step icons that we don't need until the drawer opens.+const PlaybookFlowCanvas = lazy(() =>+ import('./PlaybookFlowCanvas').then((m) => ({ default: m.PlaybookFlowCanvas })),+);++interface DAGPreviewDrawerProps {+ playbook: Playbook | null;+ onClose: () => void;+ onFork?: (pb: Playbook) => void | Promise<void>;+ forking?: boolean;+}++export function DAGPreviewDrawer({ playbook, onClose, onFork, forking }: DAGPreviewDrawerProps) {+ // Close on Escape+ useEffect(() => {+ if (!playbook) return;+ const handler = (e: KeyboardEvent) => {+ if (e.key === 'Escape') onClose();+ };+ window.addEventListener('keydown', handler);+ return () => window.removeEventListener('keydown', handler);+ }, [playbook, onClose]);++ if (!playbook) return null;++ const cat = categoryOf(playbook);+ const isPack = isShippedPack(playbook);+ const triggerLabel = describeTrigger(playbook.trigger);++ return (+ <div className="fixed inset-0 z-50 flex" role="dialog" aria-modal="true" aria-label="Playbook preview">+ {/* Backdrop */}+ <button+ type="button"+ onClick={onClose}+ aria-label="Close preview"+ className="flex-1 bg-black/60 backdrop-blur-sm"+ />++ {/* Drawer panel */}+ <aside className="w-full max-w-3xl bg-gray-950 border-l border-gray-800 shadow-2xl flex flex-col">+ {/* Header */}+ <header className="flex items-start justify-between gap-3 border-b border-gray-800 px-6 py-4">+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2 flex-wrap">+ {isPack && (+ <span+ className="text-xs font-semibold px-2 py-0.5 rounded border border-purple-700/60 bg-purple-900/40 text-purple-200"+ title="Shipped reference pack — read-only. Fork to customize."+ >+ PACK+ </span>+ )}+ {cat && (+ <span className={`text-xs px-2 py-0.5 rounded border ${categoryBadgeClass(cat)}`}>+ {categoryLabel(cat)}+ </span>+ )}+ <h2 className="text-base font-semibold text-white truncate">{playbook.name}</h2>+ <span className="text-xs text-gray-500">v{playbook.version}</span>+ </div>+ {playbook.description && (+ <p className="text-sm text-gray-400 mt-1.5">{playbook.description}</p>+ )}+ <div className="flex items-center gap-3 mt-2 text-xs text-gray-500">+ <span>{playbook.steps.length} steps</span>+ <span aria-hidden="true">·</span>+ <span>Trigger: {triggerLabel}</span>+ {playbook.author && (+ <>+ <span aria-hidden="true">·</span>+ <span>by {playbook.author}</span>+ </>+ )}+ </div>+ </div>+ <button+ onClick={onClose}+ aria-label="Close"+ className="text-gray-500 hover:text-gray-200 transition-colors text-xl leading-none px-2 py-1"+ >+ ×+ </button>+ </header>++ {/* DAG canvas — read-only */}+ <div className="flex-1 min-h-0 bg-gray-950">+ {playbook.steps.length === 0 ? (+ <div className="h-full flex items-center justify-center text-sm text-gray-600">+ This playbook has no steps yet.+ </div>+ ) : (+ <Suspense+ fallback={+ <div className="h-full flex items-center justify-center text-sm text-gray-600">+ Loading DAG preview…+ </div>+ }+ >+ <PlaybookFlowCanvas+ steps={playbook.steps}+ selectedId={null}+ onSelectStep={() => undefined}+ readOnly+ />+ </Suspense>+ )}+ </div>++ {/* Action bar */}+ <footer className="border-t border-gray-800 px-6 py-3 flex items-center justify-between">+ <p className="text-xs text-gray-500">+ {isPack+ ? 'Fork to make a local copy you can edit and enable.'+ : 'Open in editor to modify steps.'}+ </p>+ <div className="flex items-center gap-2">+ {onFork && isPack && (+ <button+ onClick={() => onFork(playbook)}+ disabled={forking}+ className="px-3 py-1.5 rounded-md bg-purple-700 hover:bg-purple-600 text-white text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {forking ? 'Forking…' : 'Fork to my playbooks'}+ </button>+ )}+ <Link+ href={`/playbooks/${playbook.id}`}+ className="px-3 py-1.5 rounded-md border border-gray-700 text-gray-200 hover:bg-gray-800 text-sm font-medium transition-colors"+ >+ {isPack ? 'View source' : 'Open editor'}+ </Link>+ </div>+ </footer>+ </aside>+ </div>+ );+}++function describeTrigger(trigger: Playbook['trigger']): string {+ if (!trigger || !trigger.on) return 'manual';+ if (trigger.on === 'schedule' && trigger.cron) return `schedule (${trigger.cron})`;+ if (trigger.on === 'alert' && trigger.severity?.length) {+ return `alert (${trigger.severity.join(', ')})`;+ }+ return trigger.on;+}diff --git a/apps/web/src/components/playbooks/PlaybooksGallery.tsx b/apps/web/src/components/playbooks/PlaybooksGallery.tsxnew file mode 100644index 000000000..cac903707--- /dev/null+++ b/apps/web/src/components/playbooks/PlaybooksGallery.tsx@@ -0,0 +1,376 @@+'use client';++/**+ * PlaybooksGallery+ * ================+ * Faceted gallery for the /playbooks "All" tab. Surfaces the 50+ shipped+ * reference packs alongside any user-created playbooks with:+ *+ * • Source filter pills ("All" / "Shipped Packs" / "Custom")+ * • Category facet chips (account-takeover, ransomware, …)+ * • Free-text search (matches name, description, tags)+ * • Per-row PACK badge (purple) + colored category badge+ * • One-click "Preview" (read-only DAG drawer)+ * • One-click "Fork" (clones a pack into a user-owned playbook)+ * • "Edit" / "Delete" (existing flow for custom playbooks)+ *+ * The gallery is driven entirely from the existing `GET /api/v1/playbooks`+ * payload — no new backend endpoints required. See packHelpers.ts for the+ * pack-detection heuristic and forking logic.+ */++import React, { useMemo, useState } from 'react';+import Link from 'next/link';+import { useRouter } from 'next/navigation';+import { mutate } from 'swr';+import clsx from 'clsx';++import type { Playbook } from './types';+import {+ PACK_CATEGORIES,+ type PackCategory,+ type PlaybookSource,+ isShippedPack,+ categoryOf,+ categoryLabel,+ categoryBadgeClass,+ filterPlaybooks,+ countBySource,+ countByCategory,+ forkPlaybook,+} from './packHelpers';+import { DAGPreviewDrawer } from './DAGPreviewDrawer';+import { EnabledToggle, RunButton, deletePlaybook } from './rowActions';++const TRIGGER_COLORS: Record<string, string> = {+ alert: 'bg-red-900/40 text-red-300 border-red-800',+ case: 'bg-blue-900/40 text-blue-300 border-blue-800',+ manual: 'bg-gray-800 text-gray-400 border-gray-700',+ schedule: 'bg-purple-900/40 text-purple-300 border-purple-800',+};++interface PlaybooksGalleryProps {+ playbooks: Playbook[];+}++export function PlaybooksGallery({ playbooks }: PlaybooksGalleryProps) {+ const router = useRouter();+ const [source, setSource] = useState<PlaybookSource>('all');+ const [category, setCategory] = useState<PackCategory | 'all'>('all');+ const [search, setSearch] = useState('');+ const [previewing, setPreviewing] = useState<Playbook | null>(null);+ const [forkingId, setForkingId] = useState<string | null>(null);+ const [forkError, setForkError] = useState<string | null>(null);++ const sourceCounts = useMemo(() => countBySource(playbooks), [playbooks]);+ const categoryCounts = useMemo(() => countByCategory(playbooks), [playbooks]);+ const filtered = useMemo(+ () => filterPlaybooks(playbooks, { source, category, search }),+ [playbooks, source, category, search],+ );++ // The category facet only meaningfully applies to packs.+ const showCategoryRow = source !== 'custom';++ async function handleFork(pb: Playbook) {+ setForkError(null);+ setForkingId(pb.id);+ try {+ const created = await forkPlaybook(pb);+ // Refresh the gallery list so the fork shows up under "Custom".+ await mutate('/api/v1/playbooks');+ // Drop the user into the editor for their fresh fork.+ setPreviewing(null);+ router.push(`/playbooks/${created.id}`);+ } catch (e) {+ setForkError(e instanceof Error ? e.message : 'Fork failed.');+ } finally {+ setForkingId(null);+ }+ }++ return (+ <div className="space-y-4">+ {/* Toolbar — search + source pills */}+ <div className="flex flex-wrap items-center gap-3">+ <div className="flex flex-1 min-w-[220px] gap-2">+ <input+ type="search"+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search playbooks by name, tag, description…"+ aria-label="Search playbooks"+ className="flex-1 rounded-lg border border-gray-700 bg-gray-900 px-3 py-2 text-sm text-gray-100 placeholder-gray-500 focus:border-blue-500 focus:outline-none"+ />+ </div>++ <div+ className="flex gap-1 rounded-lg border border-gray-700 bg-gray-900 p-1"+ role="tablist"+ aria-label="Playbook source"+ >+ <SourcePill+ label="All"+ count={sourceCounts.all}+ active={source === 'all'}+ onClick={() => setSource('all')}+ />+ <SourcePill+ label="Shipped Packs"+ count={sourceCounts.pack}+ active={source === 'pack'}+ onClick={() => setSource('pack')}+ tone="pack"+ />+ <SourcePill+ label="Custom"+ count={sourceCounts.custom}+ active={source === 'custom'}+ onClick={() => setSource('custom')}+ />+ </div>+ </div>++ {/* Category facet (only when a category is meaningful) */}+ {showCategoryRow && (+ <div className="flex flex-wrap items-center gap-2" aria-label="Filter by category">+ <CategoryPill+ label="All categories"+ active={category === 'all'}+ onClick={() => setCategory('all')}+ />+ {PACK_CATEGORIES.map((cat) => {+ const n = categoryCounts[cat];+ if (n === 0) return null;+ return (+ <CategoryPill+ key={cat}+ label={`${categoryLabel(cat)} (${n})`}+ active={category === cat}+ onClick={() => setCategory(cat)}+ tone={cat}+ />+ );+ })}+ </div>+ )}++ {forkError && (+ <div+ role="alert"+ className="rounded-md border border-red-500/30 bg-red-500/5 px-4 py-2 text-xs text-red-200"+ >+ {forkError}+ </div>+ )}++ {/* Empty state */}+ {filtered.length === 0 && (+ <div className="flex flex-col items-center justify-center py-20 text-center">+ <div className="text-lg font-medium text-gray-400 mb-2">No matching playbooks</div>+ <div className="text-sm text-gray-600 mb-6">+ Try clearing your filters, or create a new playbook from scratch.+ </div>+ <Link+ href="/playbooks/new"+ className="px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-500 text-white text-sm transition-colors"+ >+ Create a playbook+ </Link>+ </div>+ )}++ {/* List */}+ {filtered.length > 0 && (+ <div className="grid gap-3">+ {filtered.map((pb) => (+ <PlaybookRow+ key={pb.id}+ playbook={pb}+ forking={forkingId === pb.id}+ onPreview={() => setPreviewing(pb)}+ onFork={() => handleFork(pb)}+ />+ ))}+ </div>+ )}++ <DAGPreviewDrawer+ playbook={previewing}+ onClose={() => setPreviewing(null)}+ onFork={(pb) => handleFork(pb)}+ forking={forkingId !== null}+ />+ </div>+ );+}++/* ─────────────────────────── Source / Category pills ─────────────────────────── */++function SourcePill({+ label,+ count,+ active,+ onClick,+ tone,+}: {+ label: string;+ count: number;+ active: boolean;+ onClick: () => void;+ tone?: 'pack';+}) {+ return (+ <button+ role="tab"+ aria-selected={active}+ onClick={onClick}+ className={clsx(+ 'rounded px-2.5 py-1.5 text-xs font-medium transition-colors',+ active+ ? tone === 'pack'+ ? 'bg-purple-700 text-white'+ : 'bg-blue-600 text-white'+ : 'text-gray-400 hover:text-gray-200',+ )}+ >+ {label} ({count})+ </button>+ );+}++function CategoryPill({+ label,+ active,+ onClick,+ tone,+}: {+ label: string;+ active: boolean;+ onClick: () => void;+ tone?: PackCategory;+}) {+ const activeClasses = tone ? categoryBadgeClass(tone) : 'bg-blue-900/40 text-blue-200 border-blue-700';+ return (+ <button+ onClick={onClick}+ className={clsx(+ 'rounded-full px-3 py-1 text-xs font-medium border transition-colors',+ active ? activeClasses : 'border-gray-800 text-gray-500 hover:text-gray-300 hover:border-gray-700',+ )}+ >+ {label}+ </button>+ );+}++/* ─────────────────────────── Row ─────────────────────────── */++function PlaybookRow({+ playbook,+ forking,+ onPreview,+ onFork,+}: {+ playbook: Playbook;+ forking: boolean;+ onPreview: () => void;+ onFork: () => void;+}) {+ const isPack = isShippedPack(playbook);+ const cat = categoryOf(playbook);+ const triggerOn = playbook.trigger?.on ?? 'manual';++ return (+ <div+ className={clsx(+ 'bg-gray-900/60 border rounded-xl px-5 py-4 flex items-center gap-4 transition-colors',+ playbook.enabled ? 'border-gray-800 hover:border-gray-700' : 'border-gray-800/40 opacity-70',+ )}+ >+ <EnabledToggle playbook={playbook} />+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2 flex-wrap">+ {isPack && (+ <span+ className="text-[10px] font-semibold tracking-wide px-1.5 py-0.5 rounded border border-purple-700/60 bg-purple-900/40 text-purple-200"+ title="Shipped reference pack — fork to customize."+ >+ PACK+ </span>+ )}+ {cat && (+ <span+ className={`text-[10px] px-1.5 py-0.5 rounded border ${categoryBadgeClass(cat)}`}+ title={`Category: ${categoryLabel(cat)}`}+ >+ {categoryLabel(cat)}+ </span>+ )}+ <Link+ href={`/playbooks/${playbook.id}`}+ className="text-white font-medium hover:text-blue-300 transition-colors truncate"+ >+ {playbook.name}+ </Link>+ <span+ className={`text-xs px-2 py-0.5 rounded border ${+ TRIGGER_COLORS[triggerOn] ?? TRIGGER_COLORS.manual+ }`}+ >+ {triggerOn}+ </span>+ {!playbook.enabled && (+ <span className="text-xs px-1.5 py-0.5 rounded border border-gray-700 text-gray-500">+ disabled+ </span>+ )}+ </div>+ {playbook.description && (+ <p className="text-sm text-gray-500 mt-0.5 line-clamp-2">{playbook.description}</p>+ )}+ <div className="flex items-center gap-3 mt-1 text-xs text-gray-700">+ <span>{playbook.steps.length} steps</span>+ <span>v{playbook.version}</span>+ {playbook.author && <span>by {playbook.author}</span>}+ </div>+ </div>+ <div className="flex items-center gap-2 flex-shrink-0">+ <RunButton playbook={playbook} />+ <button+ onClick={onPreview}+ aria-label={`Preview DAG for ${playbook.name}`}+ className="text-xs px-2.5 py-1 rounded border border-gray-700 text-gray-300 hover:text-blue-300 hover:border-blue-800 transition-colors"+ >+ Preview+ </button>+ {isPack ? (+ <button+ onClick={onFork}+ disabled={forking}+ aria-label={`Fork ${playbook.name}`}+ className="text-xs px-2.5 py-1 rounded bg-purple-700 hover:bg-purple-600 text-white transition-colors disabled:opacity-50"+ >+ {forking ? 'Forking…' : 'Fork'}+ </button>+ ) : (+ <>+ <Link+ href={`/playbooks/${playbook.id}`}+ className="text-xs px-2.5 py-1 rounded border border-gray-700 text-gray-400 hover:text-gray-200 hover:border-gray-600 transition-colors"+ >+ Edit+ </Link>+ <button+ onClick={() => deletePlaybook(playbook.id)}+ className="text-xs px-2.5 py-1 rounded border border-gray-800 text-gray-600 hover:text-red-400 hover:border-red-900 transition-colors"+ aria-label={`Delete ${playbook.name}`}+ >+ Delete+ </button>+ </>+ )}+ </div>+ </div>+ );+}diff --git a/apps/web/src/components/playbooks/PlaybooksView.tsx b/apps/web/src/components/playbooks/PlaybooksView.tsxindex 9e87a550f..27b2bff82 100644--- a/apps/web/src/components/playbooks/PlaybooksView.tsx+++ b/apps/web/src/components/playbooks/PlaybooksView.tsx@@ -9,9 +9,10 @@import React, { useState, useCallback, useEffect } from 'react';import Link from 'next/link';-import useSWR, { mutate } from 'swr';+import useSWR from 'swr';import clsx from 'clsx';import type { Playbook, PlaybookRun } from './types';+import { PlaybooksGallery } from './PlaybooksGallery';const fetcher = (url: string) =>fetch(url).then((r) => {@@ -19,98 +20,6 @@ const fetcher = (url: string) =>return r.json();});-/* ─────────────────────────── Chips ─────────────────────────── */--const TRIGGER_COLORS: Record<string, string> = {- alert: 'bg-red-900/40 text-red-300 border-red-800',- case: 'bg-blue-900/40 text-blue-300 border-blue-800',- manual: 'bg-gray-800 text-gray-400 border-gray-700',- schedule: 'bg-purple-900/40 text-purple-300 border-purple-800',-};--function TriggerChip({ on }: { on: string }) {- return (- <span className={`text-xs px-2 py-0.5 rounded border ${TRIGGER_COLORS[on] ?? 'bg-gray-800 text-gray-400 border-gray-700'}`}>- {on}- </span>- );-}--/* ─────────────────────────── Enable Toggle ─────────────────────────── */--function EnabledToggle({ playbook }: { playbook: Playbook }) {- const [loading, setLoading] = useState(false);- async function toggle() {- setLoading(true);- try {- await fetch(`/api/v1/playbooks/${playbook.id}`, {- method: 'PUT',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ enabled: !playbook.enabled }),- });- await mutate('/api/v1/playbooks');- } finally {- setLoading(false);- }- }- return (- <button- onClick={toggle}- disabled={loading}- title={playbook.enabled ? 'Enabled — click to disable' : 'Disabled — click to enable'}- className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none disabled:opacity-50 ${- playbook.enabled ? 'bg-green-600' : 'bg-gray-700'- }`}- >- <span className={`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${playbook.enabled ? 'translate-x-4' : 'translate-x-1'}`} />- </button>- );-}--/* ─────────────────────────── Run Button ─────────────────────────── */--function RunButton({ playbook }: { playbook: Playbook }) {- const [status, setStatus] = useState<'idle' | 'running' | 'done' | 'err'>('idle');- async function run() {- setStatus('running');- try {- const res = await fetch(`/api/v1/playbooks/${playbook.id}/run`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ context: {}, dry_run: true }),- });- if (!res.ok) throw new Error();- setStatus('done');- } catch {- setStatus('err');- }- setTimeout(() => setStatus('idle'), 3000);- }- const label = { idle: 'Run', running: '…', done: 'OK', err: 'Err' }[status];- const color = {- idle: 'text-green-500 hover:text-green-400',- running: 'text-yellow-500',- done: 'text-green-400',- err: 'text-red-400',- }[status];- return (- <button- onClick={run}- disabled={status === 'running'}- title="Dry run"- className={`text-xs px-2.5 py-1 rounded border border-gray-700 transition-colors ${color}`}- >- {label}- </button>- );-}--async function deletePlaybook(id: string) {- if (!confirm('Delete this playbook?')) return;- await fetch(`/api/v1/playbooks/${id}`, { method: 'DELETE' });- await mutate('/api/v1/playbooks');-}-/* ─────────────────────────── Run History Tab ─────────────────────────── */const STATUS_BADGE: Record<string, string> = {@@ -537,59 +446,7 @@ export function PlaybooksView() {</div>)}- {data && data.length > 0 && (- <div className="grid gap-3">- {data.map((pb) => (- <div- key={pb.id}- className={`bg-gray-900/60 border rounded-xl px-5 py-4 flex items-center gap-4 transition-colors ${- pb.enabled ? 'border-gray-800 hover:border-gray-700' : 'border-gray-800/40 opacity-60'- }`}- >- <EnabledToggle playbook={pb} />- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2 flex-wrap">- <Link- href={`/playbooks/${pb.id}`}- className="text-white font-medium hover:text-blue-300 transition-colors truncate"- >- {pb.name}- </Link>- <TriggerChip on={pb.trigger.on} />- {pb.tags.slice(0, 3).map((tag) => (- <span key={tag} className="text-xs px-1.5 py-0.5 rounded bg-gray-800 text-gray-500">- {tag}- </span>- ))}- </div>- {pb.description && (- <p className="text-sm text-gray-500 mt-0.5 truncate">{pb.description}</p>- )}- <div className="flex items-center gap-3 mt-1 text-xs text-gray-700">- <span>{pb.steps.length} steps</span>- <span>v{pb.version}</span>- {pb.author && <span>by {pb.author}</span>}- </div>- </div>- <div className="flex items-center gap-2 flex-shrink-0">- <RunButton playbook={pb} />- <Link- href={`/playbooks/${pb.id}`}- className="text-xs px-2.5 py-1 rounded border border-gray-700 text-gray-400 hover:text-gray-200 hover:border-gray-600 transition-colors"- >- Edit- </Link>- <button- onClick={() => deletePlaybook(pb.id)}- className="text-xs px-2.5 py-1 rounded border border-gray-800 text-gray-600 hover:text-red-400 hover:border-red-900 transition-colors"- >- Delete- </button>- </div>- </div>- ))}- </div>- )}+ {data && data.length > 0 && <PlaybooksGallery playbooks={data} />}</>)}</div>diff --git a/apps/web/src/components/playbooks/packHelpers.test.ts b/apps/web/src/components/playbooks/packHelpers.test.tsnew file mode 100644index 000000000..63380d922--- /dev/null+++ b/apps/web/src/components/playbooks/packHelpers.test.ts@@ -0,0 +1,180 @@+/**+ * Locks in the heuristics that distinguish shipped reference packs from+ * user-created playbooks, plus the gallery filter / fork-body builders.+ * Future contributors who change PlaybookStore.create() or the pack tag+ * convention will see these tests fail.+ */++import { describe, expect, it } from 'vitest';+import type { Playbook } from './types';+import {+ isShippedPack,+ categoryOf,+ filterPlaybooks,+ countBySource,+ countByCategory,+ buildForkBody,+} from './packHelpers';++function makePlaybook(overrides: Partial<Playbook> = {}): Playbook {+ return {+ id: 'test-pack-v1',+ name: 'Test Playbook',+ description: 'Sample',+ version: '1.0.0',+ tags: [],+ trigger: { on: 'manual' },+ steps: [],+ author: 'AiSOC',+ enabled: true,+ created_at: '',+ updated_at: '',+ ...overrides,+ };+}++describe('isShippedPack', () => {+ it('classifies AiSOC-authored kebab-case ids as packs', () => {+ expect(isShippedPack(makePlaybook({ id: 'supply-vendor-breach-v1' }))).toBe(true);+ });++ it('rejects user-authored playbooks even with kebab-case ids', () => {+ expect(+ isShippedPack(makePlaybook({ id: 'my-custom-thing', author: 'alice' })),+ ).toBe(false);+ });++ it('rejects AiSOC-authored playbooks with UUID ids (treated as user copies)', () => {+ // PlaybookStore.create() generates UUIDs for forks/new playbooks.+ expect(+ isShippedPack(+ makePlaybook({ id: 'a3bb189e-8bf9-3888-9912-ace4e6543002', author: 'AiSOC' }),+ ),+ ).toBe(false);+ });++ it('rejects empty ids', () => {+ expect(isShippedPack(makePlaybook({ id: '' }))).toBe(false);+ });+});++describe('categoryOf', () => {+ it('returns the first matching category tag', () => {+ expect(categoryOf(makePlaybook({ tags: ['ransomware', 'high-severity'] }))).toBe(+ 'ransomware',+ );+ });++ it('returns null when no category tag is present', () => {+ expect(categoryOf(makePlaybook({ tags: ['high-severity'] }))).toBeNull();+ });++ it('returns null when tags is missing', () => {+ expect(categoryOf(makePlaybook({ tags: [] }))).toBeNull();+ });+});++describe('filterPlaybooks', () => {+ const corpus: Playbook[] = [+ makePlaybook({ id: 'ransomware-pack-v1', tags: ['ransomware'], name: 'Ransom A' }),+ makePlaybook({ id: 'data-exfil-pack-v1', tags: ['data-exfil'], name: 'Exfil A' }),+ makePlaybook({+ id: 'a3bb189e-8bf9-3888-9912-ace4e6543002',+ author: 'alice',+ tags: ['custom'],+ name: 'My Workflow',+ }),+ ];++ it('source=pack returns only shipped packs', () => {+ const out = filterPlaybooks(corpus, { source: 'pack', category: 'all', search: '' });+ expect(out.map((pb) => pb.id)).toEqual(['ransomware-pack-v1', 'data-exfil-pack-v1']);+ });++ it('source=custom returns only non-pack playbooks', () => {+ const out = filterPlaybooks(corpus, { source: 'custom', category: 'all', search: '' });+ expect(out.map((pb) => pb.author)).toEqual(['alice']);+ });++ it('category filter narrows packs by tag', () => {+ const out = filterPlaybooks(corpus, {+ source: 'pack',+ category: 'ransomware',+ search: '',+ });+ expect(out).toHaveLength(1);+ expect(out[0].id).toBe('ransomware-pack-v1');+ });++ it('search matches name case-insensitively', () => {+ const out = filterPlaybooks(corpus, { source: 'all', category: 'all', search: 'EXFIL' });+ expect(out).toHaveLength(1);+ expect(out[0].name).toBe('Exfil A');+ });++ it('search matches tags', () => {+ const out = filterPlaybooks(corpus, { source: 'all', category: 'all', search: 'custom' });+ expect(out).toHaveLength(1);+ expect(out[0].author).toBe('alice');+ });+});++describe('counts', () => {+ it('countBySource splits packs vs custom correctly', () => {+ const corpus: Playbook[] = [+ makePlaybook({ id: 'pack-a-v1' }),+ makePlaybook({ id: 'pack-b-v1' }),+ makePlaybook({ id: 'a3bb189e-8bf9-3888-9912-ace4e6543002', author: 'bob' }),+ ];+ expect(countBySource(corpus)).toEqual({ all: 3, pack: 2, custom: 1 });+ });++ it('countByCategory only counts packs that have a recognized tag', () => {+ const corpus: Playbook[] = [+ makePlaybook({ id: 'a-v1', tags: ['ransomware'] }),+ makePlaybook({ id: 'b-v1', tags: ['ransomware'] }),+ makePlaybook({ id: 'c-v1', tags: ['data-exfil'] }),+ makePlaybook({ id: 'd-v1', tags: ['untagged'] }),+ ];+ const out = countByCategory(corpus);+ expect(out.ransomware).toBe(2);+ expect(out['data-exfil']).toBe(1);+ expect(out['account-takeover']).toBe(0);+ });+});++describe('buildForkBody', () => {+ it('clears id, marks fork in name + tags, disables, and sets author', () => {+ const original = makePlaybook({+ id: 'ransomware-pack-v1',+ name: 'Ransomware Triage',+ tags: ['ransomware'],+ enabled: true,+ });+ const body = buildForkBody(original, { author: 'alice' });++ expect(body.id).toBe('');+ expect(body.name).toBe('Ransomware Triage (fork)');+ expect(body.author).toBe('alice');+ expect(body.enabled).toBe(false);+ expect(body.tags).toContain('fork-of:ransomware-pack-v1');+ expect(body.tags).toContain('ransomware');+ expect(body.created_at).toBe('');+ expect(body.updated_at).toBe('');+ });++ it('falls back to author "you" when not provided', () => {+ const body = buildForkBody(makePlaybook({ id: 'pack-x-v1' }));+ expect(body.author).toBe('you');+ });++ it('does not duplicate the fork-of marker on chained forks', () => {+ const original = makePlaybook({+ id: 'pack-y-v1',+ tags: ['ransomware', 'fork-of:pack-y-v1'],+ });+ const body = buildForkBody(original);+ const occurrences = body.tags.filter((t) => t === 'fork-of:pack-y-v1').length;+ expect(occurrences).toBe(1);+ });+});diff --git a/apps/web/src/components/playbooks/packHelpers.ts b/apps/web/src/components/playbooks/packHelpers.tsnew file mode 100644index 000000000..cab779424--- /dev/null+++ b/apps/web/src/components/playbooks/packHelpers.ts@@ -0,0 +1,196 @@+/**+ * packHelpers+ * ===========+ * Helpers for distinguishing AiSOC's shipped reference playbook packs from+ * user-created playbooks, deriving category facets, and forking a pack.+ *+ * Design notes:+ * - The agents service loads both user-created playbooks and the+ * `playbooks/packs/v1/**` reference packs into a single flat list at+ * `GET /api/v1/playbooks` (see services/agents/app/playbook/store.py).+ * - Shipped packs all carry `author === "AiSOC"` and use kebab-case ids+ * like `supply-vendor-breach-v1`. User-created playbooks default to a+ * UUID id (PlaybookStore.create generates one when id is empty).+ * - We treat a playbook as a "pack" when the author matches AND the id+ * does not look like a UUID. This avoids misclassifying any future+ * user-submitted playbook that happens to set author="AiSOC".+ * - Categories are recovered from the first matching tag — packs all+ * prefix their tags with the category name (see playbooks/packs/v1).+ */++import type { Playbook } from './types';++const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/** The 8 reference-pack categories shipped under playbooks/packs/v1. */+export const PACK_CATEGORIES = [+ 'account-takeover',+ 'cloud-misconfig',+ 'data-exfil',+ 'identity-compromise',+ 'malware-detection',+ 'network-anomaly',+ 'ransomware',+ 'supply-chain',+] as const;++export type PackCategory = (typeof PACK_CATEGORIES)[number];++const CATEGORY_LABELS: Record<PackCategory, string> = {+ 'account-takeover': 'Account Takeover',+ 'cloud-misconfig': 'Cloud Misconfig',+ 'data-exfil': 'Data Exfil',+ 'identity-compromise': 'Identity',+ 'malware-detection': 'Malware',+ 'network-anomaly': 'Network',+ ransomware: 'Ransomware',+ 'supply-chain': 'Supply Chain',+};++const CATEGORY_COLORS: Record<PackCategory, string> = {+ 'account-takeover': 'bg-orange-900/40 text-orange-300 border-orange-800',+ 'cloud-misconfig': 'bg-cyan-900/40 text-cyan-300 border-cyan-800',+ 'data-exfil': 'bg-pink-900/40 text-pink-300 border-pink-800',+ 'identity-compromise': 'bg-blue-900/40 text-blue-300 border-blue-800',+ 'malware-detection': 'bg-red-900/40 text-red-300 border-red-800',+ 'network-anomaly': 'bg-teal-900/40 text-teal-300 border-teal-800',+ ransomware: 'bg-rose-900/40 text-rose-300 border-rose-800',+ 'supply-chain': 'bg-amber-900/40 text-amber-300 border-amber-800',+};++/**+ * True when the playbook is one of the shipped reference packs that lives+ * under `playbooks/packs/v1/`. Heuristic: author "AiSOC" + non-UUID id.+ */+export function isShippedPack(pb: Playbook): boolean {+ if (pb.author !== 'AiSOC') return false;+ if (!pb.id) return false;+ return !UUID_REGEX.test(pb.id);+}++/**+ * Returns the pack category (account-takeover, ransomware, …) inferred+ * from the playbook's tags, or null when the playbook does not fit one+ * of the known categories.+ */+export function categoryOf(pb: Playbook): PackCategory | null {+ const tags = pb.tags ?? [];+ for (const tag of tags) {+ if ((PACK_CATEGORIES as readonly string[]).includes(tag)) {+ return tag as PackCategory;+ }+ }+ return null;+}++/** Human-readable label for a pack category. */+export function categoryLabel(cat: PackCategory): string {+ return CATEGORY_LABELS[cat];+}++/** Tailwind classes for a category badge. */+export function categoryBadgeClass(cat: PackCategory): string {+ return CATEGORY_COLORS[cat];+}++/** Source classification used by the gallery filter pills. */+export type PlaybookSource = 'all' | 'pack' | 'custom';++/** Apply gallery filters (source + category + search) to a playbook list. */+export function filterPlaybooks(+ playbooks: Playbook[],+ filters: { source: PlaybookSource; category: PackCategory | 'all'; search: string },+): Playbook[] {+ const q = filters.search.trim().toLowerCase();+ return playbooks.filter((pb) => {+ const isPack = isShippedPack(pb);+ if (filters.source === 'pack' && !isPack) return false;+ if (filters.source === 'custom' && isPack) return false;+ if (filters.category !== 'all') {+ const cat = categoryOf(pb);+ if (cat !== filters.category) return false;+ }+ if (q) {+ const haystack = [pb.name, pb.description, ...(pb.tags ?? [])]+ .filter(Boolean)+ .join(' ')+ .toLowerCase();+ if (!haystack.includes(q)) return false;+ }+ return true;+ });+}++/**+ * Counts of playbooks per source bucket (used to render the source pills).+ */+export function countBySource(playbooks: Playbook[]): { all: number; pack: number; custom: number } {+ let pack = 0;+ let custom = 0;+ for (const pb of playbooks) {+ if (isShippedPack(pb)) pack += 1;+ else custom += 1;+ }+ return { all: playbooks.length, pack, custom };+}++/**+ * Counts of pack playbooks per category (used to render the category pills).+ */+export function countByCategory(playbooks: Playbook[]): Record<PackCategory, number> {+ const out: Record<PackCategory, number> = {+ 'account-takeover': 0,+ 'cloud-misconfig': 0,+ 'data-exfil': 0,+ 'identity-compromise': 0,+ 'malware-detection': 0,+ 'network-anomaly': 0,+ 'ransomware': 0,+ 'supply-chain': 0,+ };+ for (const pb of playbooks) {+ const cat = categoryOf(pb);+ if (cat) out[cat] += 1;+ }+ return out;+}++/**+ * Build the JSON body for forking a shipped pack into a user-owned copy.+ * The agents service generates a fresh UUID when `id` is empty (see+ * PlaybookStore.create). We disable the fork by default so it doesn't+ * fire on the next matching alert before the operator reviews it.+ */+export function buildForkBody(original: Playbook, opts?: { author?: string }): Playbook {+ return {+ ...original,+ id: '',+ name: `${original.name} (fork)`,+ author: opts?.author ?? 'you',+ enabled: false,+ tags: Array.from(new Set([...(original.tags ?? []), `fork-of:${original.id}`])),+ created_at: '',+ updated_at: '',+ };+}++/**+ * POST a forked playbook to the agents API. Returns the created Playbook+ * (with a freshly assigned UUID) or throws on failure.+ */+export async function forkPlaybook(+ original: Playbook,+ opts?: { author?: string },+): Promise<Playbook> {+ const body = buildForkBody(original, opts);+ const res = await fetch('/api/v1/playbooks', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });+ if (!res.ok) {+ const text = await res.text().catch(() => '');+ throw new Error(`Fork failed: HTTP ${res.status}${text ? ` — ${text}` : ''}`);+ }+ return (await res.json()) as Playbook;+}diff --git a/apps/web/src/components/playbooks/rowActions.tsx b/apps/web/src/components/playbooks/rowActions.tsxnew file mode 100644index 000000000..403e9da07--- /dev/null+++ b/apps/web/src/components/playbooks/rowActions.tsx@@ -0,0 +1,94 @@+'use client';++/**+ * Shared per-row action primitives for the Playbooks page.+ *+ * Extracted from PlaybooksView.tsx so the gallery can reuse them without a+ * circular import. The original behavior is preserved exactly (same fetch+ * URLs, same SWR cache keys, same UX).+ */++import React, { useState } from 'react';+import { mutate } from 'swr';+import type { Playbook } from './types';++/** Small toggle that flips Playbook.enabled via PUT /api/v1/playbooks/<id>. */+export function EnabledToggle({ playbook }: { playbook: Playbook }) {+ const [loading, setLoading] = useState(false);+ async function toggle() {+ setLoading(true);+ try {+ await fetch(`/api/v1/playbooks/${playbook.id}`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ enabled: !playbook.enabled }),+ });+ await mutate('/api/v1/playbooks');+ } finally {+ setLoading(false);+ }+ }+ return (+ <button+ onClick={toggle}+ disabled={loading}+ title={playbook.enabled ? 'Enabled — click to disable' : 'Disabled — click to enable'}+ aria-label={`${playbook.enabled ? 'Disable' : 'Enable'} ${playbook.name}`}+ aria-pressed={playbook.enabled}+ className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1 focus:ring-offset-gray-900 disabled:opacity-50 ${+ playbook.enabled ? 'bg-green-600' : 'bg-gray-700'+ }`}+ >+ <span+ className={`inline-block h-3.5 w-3.5 rounded-full bg-white transition-transform ${+ playbook.enabled ? 'translate-x-4' : 'translate-x-1'+ }`}+ />+ </button>+ );+}++/** "Run" / dry-run button that POSTs to /api/v1/playbooks/<id>/run. */+export function RunButton({ playbook }: { playbook: Playbook }) {+ const [status, setStatus] = useState<'idle' | 'running' | 'done' | 'err'>('idle');+ async function run() {+ setStatus('running');+ try {+ const res = await fetch(`/api/v1/playbooks/${playbook.id}/run`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ context: {}, dry_run: true }),+ });+ if (!res.ok) throw new Error();+ setStatus('done');+ } catch {+ setStatus('err');+ }+ setTimeout(() => setStatus('idle'), 3000);+ }+ const label = { idle: 'Run', running: '…', done: 'OK', err: 'Err' }[status];+ const color = {+ idle: 'text-green-500 hover:text-green-400',+ running: 'text-yellow-500',+ done: 'text-green-400',+ err: 'text-red-400',+ }[status];+ return (+ <button+ onClick={run}+ disabled={status === 'running'}+ title="Dry run"+ aria-label={`Dry-run ${playbook.name}`}+ className={`text-xs px-2.5 py-1 rounded border border-gray-700 transition-colors ${color}`}+ >+ {label}+ </button>+ );+}++/** Delete a playbook (used only for user-created playbooks, not shipped packs). */+export async function deletePlaybook(id: string) {+ if (!confirm('Delete this playbook?')) return;+ await fetch(`/api/v1/playbooks/${id}`, { method: 'DELETE' });+ await mutate('/api/v1/playbooks');+}