A modern platform for visual, flexible, and extensible graph-based investigations. For cybersecurity analysts and investigators.
feat: add edge
dextmorgndbc41d8bf39d
diff --git a/flowsint-api/app/api/routes/sketches.py b/flowsint-api/app/api/routes/sketches.pyindex 8ec5f5f8..414f8b03 100644--- a/flowsint-api/app/api/routes/sketches.py+++ b/flowsint-api/app/api/routes/sketches.py@@ -1,6 +1,6 @@from fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel-from typing import Dict, Any+from typing import Dict, Any, Literalfrom fastapi import HTTPExceptionfrom pydantic import BaseModel, Fieldfrom app.utils import flatten@@ -51,8 +51,6 @@ async def get_sketch_nodes(sketch_id: str):"label": record["data"].get("label", "Node"),"type": record["labels"][0].lower(),"caption": record["data"].get("label", "Node"),- "size": 40,- "color": record["data"].get("color", "#FFFFFF"),"x": random.random() * 1000,"y": random.random() * 1000}@@ -67,8 +65,6 @@ async def get_sketch_nodes(sketch_id: str):"to": str(record["target"]),"data": record["data"],"caption": record["type"],- "width": 1,- "color": "#A5ABB6"}for record in rels_result]@@ -80,8 +76,8 @@ class NodeInput(BaseModel):type: strdata: Dict[str, Any] = Field(default_factory=dict)-def dict_to_cypher_props(props: dict) -> str:- return ", ".join(f"{key}: ${key}" for key in props)+def dict_to_cypher_props(props: dict, prefix: str = "") -> str:+ return ", ".join(f"{key}: ${prefix}{key}" for key in props)# Endpoints@router.get("/sketches")@@ -136,29 +132,25 @@ def add_node(sketch_id: str, node: NodeInput):"node": new_node,}-class EdgeInput(BaseModel):- from_node: dict- to_node: dict- type: str-[email protected]("/sketch/{sketch_id}/edges/add")-def add_edge(sketch_id: str, edge: EdgeInput):- from_props = flatten(edge.from_node)- to_props = flatten(edge.to_node)+class RelationInput(BaseModel):+ source: Any+ target: Any+ type: Literal["one-way", "two-way"]+ label: str = "RELATED_TO" # Optionnel : nom de la relation- from_cypher = dict_to_cypher_props(from_props)- to_cypher = dict_to_cypher_props(to_props)[email protected]("/sketch/{sketch_id}/relations/add")+def add_edge(sketch_id: str, relation: RelationInput):query = f"""- MATCH (a {{ {from_cypher} }})- MATCH (b {{ {to_cypher} }})- MERGE (a)-[r:`{edge.type}` {{sketch_id: $sketch_id}}]->(b)+ MATCH (a) WHERE elementId(a) = $from_id+ MATCH (b) WHERE elementId(b) = $to_id+ MERGE (a)-[r:`{relation.label}` {{sketch_id: $sketch_id}}]->(b)RETURN r"""params = {- **from_props,- **to_props,+ "from_id": relation.source["id"],+ "to_id": relation.target["id"],"sketch_id": sketch_id,}@@ -167,11 +159,12 @@ def add_edge(sketch_id: str, edge: EdgeInput):except Exception as e:print(f"Edge creation error: {e}")raise HTTPException(status_code=500, detail="Failed to create edge")-+ print(result)if not result:raise HTTPException(status_code=400, detail="Edge creation failed")return {"status": "edge added","edge": result[0]["r"],- }\ No newline at end of file+ }+diff --git a/flowsint-api/app/core/celery.py b/flowsint-api/app/core/celery.pyindex 430000ba..3c584f5e 100644--- a/flowsint-api/app/core/celery.py+++ b/flowsint-api/app/core/celery.py@@ -2,7 +2,7 @@ from celery import Celerycelery_app = Celery("flowsint",- broker="redis://127.0.0.1:6379/0",- backend="redis://127.0.0.1:6379/0",+ broker="redis://redis:6379/0",+ backend="redis://redis:6379/0",include=["app.tasks.transform"])\ No newline at end of filediff --git a/flowsint-api/app/scanners/domains/resolve.py b/flowsint-api/app/scanners/domains/resolve.pyindex 1e09b823..51893b0f 100644--- a/flowsint-api/app/scanners/domains/resolve.py+++ b/flowsint-api/app/scanners/domains/resolve.py@@ -84,7 +84,6 @@ class ResolveScanner(Scanner):MERGE (ip:ip {address: $ip})SET ip.sketch_id = $sketch_idSET ip.label = $label- SET ip.color = $colorSET ip.caption = $captionSET ip.type = $typeMERGE (d)-[:RESOLVES_TO {sketch_id: $sketch_id}]->(ip)@@ -94,7 +93,6 @@ class ResolveScanner(Scanner):"domain": domain_obj.domain,"ip": ip_obj.address,"sketch_id": self.sketch_id,- "color": '#5533FF',"label": ip_obj.address,"caption": ip_obj.address,"type": "ip"diff --git a/flowsint-api/app/scanners/domains/subdomains.py b/flowsint-api/app/scanners/domains/subdomains.pyindex bdaeb246..2715c7ab 100644--- a/flowsint-api/app/scanners/domains/subdomains.py+++ b/flowsint-api/app/scanners/domains/subdomains.py@@ -144,7 +144,6 @@ class SubdomainScanner(Scanner):MERGE (sub:domain {domain: $subdomain})SET sub.sketch_id = $sketch_id,sub.label = $label,- sub.color = $color,sub.caption = $caption,sub.type = $typeMERGE (d:domain {domain: $domain})@@ -155,7 +154,6 @@ class SubdomainScanner(Scanner):"sketch_id": self.sketch_id,"label": subdomain,"caption": subdomain,- "color": "#865FCD","type": "subdomain"})logger.info(self.scan_id, self.sketch_id, f"{domain_obj.domain} -> {len(domain_obj.subdomains)} subdomain(s) found.")diff --git a/flowsint-api/app/scanners/orchestrator.py b/flowsint-api/app/scanners/orchestrator.pyindex 5b87dbf6..935f9e5f 100644--- a/flowsint-api/app/scanners/orchestrator.py+++ b/flowsint-api/app/scanners/orchestrator.py@@ -160,7 +160,7 @@ class TransformOrchestrator(Scanner):results_mapping = {}# Process each branch- for branch in self.reorder_branches():+ for branch in self.transform_branches:branch_id = branch.idbranch_name = branch.namebranch_results = {diff --git a/flowsint-api/app/utils.py b/flowsint-api/app/utils.pyindex 853f036e..755f002e 100644--- a/flowsint-api/app/utils.py+++ b/flowsint-api/app/utils.py@@ -174,7 +174,7 @@ def get_label_color(label: str) -> str:return color_map.get(label, color_map["default"])-def flatten(data_dict):+def flatten(data_dict, prefix=""):"""Flattens a dictionary to contain only Neo4j-compatible property values.Neo4j supports primitive types (string, number, boolean) and arrays of those types.@@ -192,5 +192,6 @@ def flatten(data_dict):if isinstance(value, (str, int, float, bool)) or (isinstance(value, list) and all(isinstance(item, (str, int, float, bool)) for item in value)):+ key = f"{prefix}{key}"flattened[key] = valuereturn flatteneddiff --git a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/2d-graph.tsx b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/2d-graph.tsxindex 35387f5b..bf357124 100644--- a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/2d-graph.tsx+++ b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/2d-graph.tsx@@ -287,6 +287,7 @@ const Graph = ({ data, isLoading, width, height }: GraphProps) => {handleGraphRef(instance);if (currentNode) handleGraphInstance(instance);}}+ cooldownTicks={100}graphData={{ nodes, links: edges }}nodeId="id"linkSource="from"diff --git a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/client.tsx b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/client.tsxindex 4599e273..f87881cb 100644--- a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/client.tsx+++ b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/client.tsx@@ -12,6 +12,7 @@ import { useSketchStore } from "@/store/sketch-store"import { GraphPanel } from "./graph-panel"import { Sketch } from "@/types/sketch"import SettingsModal from "./settings-modal"+import { CreateRelationDialog } from "@/components/sketches/sketch/create-relation"interface DashboardClientProps {investigationId: string@@ -67,6 +68,7 @@ export default function DashboardClient({ investigationId, sketchId, sketch, use/></ResizablePanelGroup></div>+ <CreateRelationDialog sketchId={sketchId} /><SettingsModal /></>)diff --git a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/toolbar.tsx b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/toolbar.tsxindex 9208c2d6..e7486064 100644--- a/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/toolbar.tsx+++ b/flowsint-web/src/app/dashboard/investigations/[investigation_id]/sketches/[sketch_id]/toolbar.tsx@@ -1,7 +1,6 @@"use client"import { AvatarList } from "@/components/avatar-list"-import { DownloadButton } from "@/components/download-button"import MoreMenu from "@/components/sketches/more-menu"import { ScanButton } from "@/components/sketches/scans-drawer/scan-button"import { Button } from "@/components/ui/button"@@ -19,6 +18,7 @@ import {ArrowDownUp,Copy,Filter,+ GitBranchIcon,Layers,LayoutGrid,Maximize,@@ -32,7 +32,7 @@ import {} from "lucide-react"import { notFound } from "next/navigation"import { useQueryState } from "nuqs"-import { memo, useMemo } from "react"+import { memo, useCallback, useMemo } from "react"import { shallow } from "zustand/shallow"@@ -81,12 +81,9 @@ export const Toolbar = memo(function Toolbar({user_id: string;}) {- const { currentNode } = useSketchStore(- state => ({- currentNode: state.currentNode,- }),- shallow- )+ const selectedNodes = useSketchStore((state) => state.selectedNodes || [])+ const openAddRelationDialog = useSketchStore((state) => state.openAddRelationDialog)+ const setOpenAddRelationDialog = useSketchStore((state) => state.setOpenAddRelationDialog)const toggleSettings = useModalStore((s) => s.toggleSettings)const zoomToFit = useGraphControls((s) => s.zoomToFit);const zoomIn = useGraphControls((s) => s.zoomIn);@@ -106,6 +103,10 @@ export const Toolbar = memo(function Toolbar({refetchOnWindowFocus: true,})+ const handleOpenRelationshipDialog = useCallback(() => {+ setOpenAddRelationDialog(true)+ }, [])+// Memoize sketch members to prevent unnecessary rerendersconst sketchMembers = useMemo(() =>@@ -115,6 +116,8 @@ export const Toolbar = memo(function Toolbar({})) || [],[sketch?.members, sketch?.owner_id])+ const isMoreThanZero = selectedNodes.length > 0+ const isTwo = selectedNodes.length == 2return (<div className="flex items-center justify-between h-10 border-b px-2 bg-card">@@ -126,12 +129,18 @@ export const Toolbar = memo(function Toolbar({<ToolbarButtonicon={<Copy className="h-4 w-4 opacity-70" />}tooltip="Copy"- disabled={!currentNode}+ disabled={!isMoreThanZero}+ />+ <ToolbarButton+ onClick={handleOpenRelationshipDialog}+ icon={<GitBranchIcon className="h-4 w-4 opacity-70" />}+ tooltip="Create relation"+ disabled={!isTwo}/><ToolbarButtonicon={<Trash className="h-4 w-4 opacity-70" />}tooltip="Delete"- disabled={!currentNode}+ disabled={!isMoreThanZero}/><Separator /><ToolbarButton disabled icon={<ArrowDownUp className="h-4 w-4 opacity-70" />} tooltip="Arrange" />diff --git a/flowsint-web/src/app/dashboard/transforms/page.tsx b/flowsint-web/src/app/dashboard/transforms/page.tsxindex 78ebbf87..a4368f8c 100644--- a/flowsint-web/src/app/dashboard/transforms/page.tsx+++ b/flowsint-web/src/app/dashboard/transforms/page.tsx@@ -14,7 +14,7 @@ const TransformsPage = async () => {<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4"><div><h1 className="font-semibold text-2xl">Transforms {transforms?.length ? `(${transforms.length})` : ""}</h1>- <p className="text-muted-foreground mt-1">Manage your data transformation workflows</p>+ <p className="text-muted-foreground mt-1">Manage your data transformation workflows.</p></div>{transforms?.length !== 0 &&<Link href="/dashboard/transforms/editor">diff --git a/flowsint-web/src/app/layout.tsx b/flowsint-web/src/app/layout.tsxindex 0d922f0c..60ef6b86 100644--- a/flowsint-web/src/app/layout.tsx+++ b/flowsint-web/src/app/layout.tsx@@ -42,14 +42,14 @@ export default function RootLayout({}) {return (<html suppressHydrationWarning lang="en" className={inter.className}>- {/* <head>+ <head>{process.env.NODE_ENV === "development" && (<scriptcrossOrigin="anonymous"src="//unpkg.com/react-scan/dist/auto.global.js"/>)}- </head> */}+ </head><bodyclassName={clsx("min-h-screen !bg-background font-sans antialiased",diff --git a/flowsint-web/src/components/dashboard/new-sketch.tsx b/flowsint-web/src/components/dashboard/new-sketch.tsxindex 407780e5..30d33520 100644--- a/flowsint-web/src/components/dashboard/new-sketch.tsx+++ b/flowsint-web/src/components/dashboard/new-sketch.tsx@@ -20,6 +20,7 @@ import { Label } from "@/components/ui/label"import { useFormStatus } from "react-dom"import { toast } from "sonner"import { useInvestigationStore } from "@/store/investigation-store"+import { DialogTrigger } from "@radix-ui/react-dialog"function SubmitButton() {const { pending } = useFormStatus()@@ -51,8 +52,8 @@ export default function NewSketch({ children, noDropDown = false }: { children:if (noDropDown) return (<>- <Button asChild onClick={() => setOpen(true)}>{children}</Button><Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger asChild onClick={() => setOpen(true)}>{children}</DialogTrigger><DialogContent className="sm:max-w-[425px]"><DialogHeader><DialogTitle>New sketch</DialogTitle>@@ -61,7 +62,7 @@ export default function NewSketch({ children, noDropDown = false }: { children:<form action={handleNewSketch}><div className="grid gap-4 py-4"><div className="grid gap-2">- <Label htmlFor="title">Investigation name</Label>+ <Label htmlFor="title">Sketch name</Label><Input id="title" name="title" placeholder="Suspicion de fraude" required /></div><div className="grid gap-2">@@ -69,7 +70,7 @@ export default function NewSketch({ children, noDropDown = false }: { children:<Inputid="description"name="description"- placeholder="Investigation sur une campagne de phishing via LinkedIn."+ placeholder="Fishing domain external scope"/></div></div>diff --git a/flowsint-web/src/components/sketches/new-actions.tsx b/flowsint-web/src/components/sketches/new-actions.tsxindex 2afc2e0d..3ab86c99 100644--- a/flowsint-web/src/components/sketches/new-actions.tsx+++ b/flowsint-web/src/components/sketches/new-actions.tsx@@ -169,7 +169,7 @@ function ActionCard({ item, onSelect }: ActionCardProps) {<div className="font-medium text-sm">{item.label}</div>{item.disabled && (<Badge variant="outline" className="mt-2 absolute top-2 left-2">- bientôt+ Soon</Badge>)}{item.children && (diff --git a/flowsint-web/src/components/sketches/sketch-selector.tsx b/flowsint-web/src/components/sketches/sketch-selector.tsxindex 2f766b7f..fa2db652 100644--- a/flowsint-web/src/components/sketches/sketch-selector.tsx+++ b/flowsint-web/src/components/sketches/sketch-selector.tsx@@ -12,6 +12,7 @@ import { Skeleton } from "@/components/ui/skeleton";import { WaypointsIcon } from "lucide-react";import { Badge } from "../ui/badge";+export default function CaseSelector() {const router = useRouter()const { sketch_id, investigation_id } = useParams()diff --git a/flowsint-web/src/components/sketches/sketch/create-relation.tsx b/flowsint-web/src/components/sketches/sketch/create-relation.tsxnew file mode 100644index 00000000..7da32202--- /dev/null+++ b/flowsint-web/src/components/sketches/sketch/create-relation.tsx@@ -0,0 +1,141 @@+"use client"++import type React from "react"++import { useState } from "react"+import { useSketchStore } from "@/store/sketch-store"+import { Button } from "@/components/ui/button"+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"+import { Input } from "@/components/ui/input"+import { ArrowRight, ArrowLeftRight } from "lucide-react"+import { Badge } from "@/components/ui/badge"+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"+import { saveEdge } from "@/lib/actions/sketches"+import { toast } from "sonner"++export function CreateRelationDialog({ sketchId }: { sketchId: string }) {+ const selectedNodes = useSketchStore((state) => state.selectedNodes || [])+ const openAddRelationDialog = useSketchStore((state) => state.openAddRelationDialog)+ const setOpenAddRelationDialog = useSketchStore((state) => state.setOpenAddRelationDialog)+ const [relationType, setRelationType] = useState("")+ const [direction, setDirection] = useState<"one-way" | "two-way">("one-way")++ const handleSubmit = async (e: { preventDefault: () => void }) => {+ e.preventDefault()+ try {+ const schema = {+ source: selectedNodes[0],+ target: selectedNodes[1],+ type: direction,+ label: relationType,+ sketch_id: sketchId+ }+ const resp = await saveEdge(schema)+ // if (addEdges) addEdges(schema)+ setOpenAddRelationDialog(false)+ toast.success("Relation successfully added.")+ } catch (error) {+ toast.error("Unexpected error during node creation.")+ } finally {+ setOpenAddRelationDialog(false)+ }+ }++ const getNodeDisplayName = (node: any) => {+ return node.data?.label || node.data?.username || node.id+ }++ return (+ <Dialog open={openAddRelationDialog} onOpenChange={setOpenAddRelationDialog}>+ <DialogContent className="!w-full !max-w-[730px]">+ <DialogHeader>+ <DialogTitle>New relationship</DialogTitle>+ </DialogHeader>+ <form onSubmit={handleSubmit} className="space-y-6">+ <Tabs+ defaultValue="one-way"+ className="w-full"+ onValueChange={(value) => setDirection(value as "one-way" | "two-way")}+ >+ <TabsList className="grid w-full grid-cols-2">+ <TabsTrigger value="one-way" className="flex items-center justify-center gap-2">+ <ArrowRight className="h-4 w-4" />+ <span>One-way</span>+ </TabsTrigger>+ <TabsTrigger value="two-way" className="flex items-center justify-center gap-2">+ <ArrowLeftRight className="h-4 w-4" />+ <span>Two-way</span>+ </TabsTrigger>+ </TabsList>+ <TabsContent value="one-way" className="mt-4">+ <div className="flex items-center gap-2 p-4 border justify-between rounded-lg bg-background">+ <div className="flex-col min-w-0 items-start">+ <div className="text-xs font-medium mb-2">From</div>+ <div className="flex flex-wrap gap-1">+ {selectedNodes.slice(0, selectedNodes.length - 1).map((node) => (+ <Badge key={node.id} variant="outline" className="max-w-full truncate">+ {getNodeDisplayName(node)}+ </Badge>+ ))}+ </div>+ </div>+ <div className="flex flex-col w-full items-center justify-center px-2">+ <ArrowRight className="h-5 w-5 text-muted-foreground my-1" />+ <Input+ placeholder="IS_RELATED_TO"+ className="w-2/3 mx-auto text-center text-sm"+ value={relationType}+ onChange={(e) => setRelationType(e.target.value)}+ required+ />+ </div>+ <div className="flex-col min-w-0 items-end">+ <div className="text-xs font-medium mb-2">To</div>+ <div className="flex flex-wrap gap-1">+ {selectedNodes.slice(-1).map((node) => (+ <Badge key={node.id} variant="outline" className="max-w-full truncate">+ {getNodeDisplayName(node)}+ </Badge>+ ))}+ </div>+ </div>+ </div>+ </TabsContent>+ <TabsContent value="two-way" className="mt-4">+ <div className="flex items-center gap-2 p-4 border rounded-lg bg-background">+ <div className="flex-1 min-w-0">+ <div className="text-xs font-medium mb-2">Nodes</div>+ <div className="flex flex-wrap gap-1">+ {selectedNodes.map((node) => (+ <Badge key={node.id} variant="outline" className="max-w-full truncate">+ {getNodeDisplayName(node)}+ </Badge>+ ))}+ </div>+ </div>+ <div className="flex flex-col items-center px-2">+ <ArrowLeftRight className="h-5 w-5 text-muted-foreground my-1" />+ <Input+ placeholder="Type de relation"+ className="w-32 text-center text-sm"+ value={relationType}+ onChange={(e) => setRelationType(e.target.value)}+ required+ />+ </div>+ </div>+ </TabsContent>+ </Tabs>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => setOpenAddRelationDialog(false)}>+ Cancel+ </Button>+ <Button type="submit" disabled={!relationType.trim()}>+ Create+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ )+}diff --git a/flowsint-web/src/components/sketches/sketch/nodes-panel.tsx b/flowsint-web/src/components/sketches/sketch/nodes-panel.tsxindex be46918a..e768959b 100644--- a/flowsint-web/src/components/sketches/sketch/nodes-panel.tsx+++ b/flowsint-web/src/components/sketches/sketch/nodes-panel.tsx@@ -1,110 +1,159 @@-import React, { memo, useMemo, useState, useCallback } from 'react'-import { useSketchStore } from '@/store/sketch-store'-import { Button } from '@/components/ui/button'-import { Badge } from '@/components/ui/badge'-import { TypeBadge } from '@/components/type-badge'+"use client"++import type React from "react"+import { memo, useMemo, useState, useCallback } from "react"+import { useSketchStore } from "@/store/sketch-store"+import { Button } from "@/components/ui/button"+import { Badge } from "@/components/ui/badge"+import { TypeBadge } from "@/components/type-badge"import { Search, HelpCircle, FilterIcon, XIcon } from "lucide-react"-import { usePlatformIcons } from '@/lib/hooks/use-platform-icons'-import { Input } from '@/components/ui/input'-import { actionItems } from '@/lib/action-items'-import { cn } from '@/lib/utils'-import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'-import Loader from '@/components/loader'-import { IconContainer } from '@/components/icon-container'-import { NodeData } from '@/types'+import { usePlatformIcons } from "@/lib/hooks/use-platform-icons"+import { Input } from "@/components/ui/input"+import { actionItems } from "@/lib/action-items"+import { cn } from "@/lib/utils"+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu"+import Loader from "@/components/loader"+import type { NodeData } from "@/types"+import { Checkbox } from "@/components/ui/checkbox"// Mémoiser le composant SocialNode-const SocialNode = memo(({ node, setCurrentNode, isSelected }: {- node: any,- setCurrentNode: (node: NodeData) => void,- isSelected: any-}) => {- const platformsIcons = usePlatformIcons()- const platformIcon = useMemo(() => {- // @ts-ignore- return platformsIcons?.[node?.data?.platform]?.icon- }, [platformsIcons, node?.data?.platform])-- const handleClick = useCallback(() => setCurrentNode(node), [node, setCurrentNode])+const SocialNode = memo(+ ({+ node,+ setCurrentNode,+ isSelected,+ onCheckboxChange,+ isNodeChecked,+ }: {+ node: any+ setCurrentNode: (node: NodeData) => void+ isSelected: any+ onCheckboxChange: (node: NodeData, checked: boolean) => void+ isNodeChecked: (nodeId: string) => boolean+ }) => {+ const platformsIcons = usePlatformIcons()+ const platformIcon = useMemo(() => {+ // @ts-ignore+ return platformsIcons?.[node?.data?.platform]?.icon+ }, [platformsIcons, node?.data?.platform])- return (- <Button- variant={"ghost"}- className={cn(- 'flex items-center justify-start p-4 !py-5 rounded-none text-left border-b border-l-2 border-l-transparent',- isSelected(node.id) && 'border-l-primary bg-background'- )}- onClick={handleClick}- >- <Badge variant="secondary" className="h-7 w-7 p-0 rounded-full">- {platformIcon}- </Badge>- <div className='grow truncate text-ellipsis'>- {node?.data?.username || <span className='italic opacity-60'>Unknown</span>}+ const handleClick = useCallback(() => setCurrentNode(node), [node, setCurrentNode])++ const handleCheckboxChange = useCallback(+ (checked: boolean) => {+ onCheckboxChange(node, checked)+ },+ [node, onCheckboxChange],+ )++ return (+ <div className="flex items-center border-b">+ <div className="pl-2">+ <Checkbox checked={isNodeChecked(node.id)} onCheckedChange={handleCheckboxChange} className="mr-1" />+ </div>+ <Button+ variant={"ghost"}+ className={cn(+ "flex-1 flex items-center justify-start p-4 !py-5 rounded-none text-left border-l-2 border-l-transparent",+ isSelected(node.id) && "border-l-primary bg-background",+ )}+ onClick={handleClick}+ >+ <Badge variant="secondary" className="h-7 w-7 p-0 rounded-full">+ {platformIcon}+ </Badge>+ <div className="grow truncate text-ellipsis">+ {node?.data?.username || <span className="italic opacity-60">Unknown</span>}+ </div>+ <TypeBadge type={node?.data?.type as string} />+ </Button></div>- <TypeBadge type={node?.data?.type as string} />- </Button>- )-})+ )+ },+)// Mémoiser le composant NodeRenderer-const NodeRenderer = memo(({- node,- setCurrentNode,- isSelected-}: {- node: any,- setCurrentNode: (node: NodeData) => void,- isSelected: any-}) => {- const item = useMemo(() =>- (actionItems as any).find((a: any) => a?.type === node.data?.type),- [node.data?.type]- )- const Icon = item?.icon || HelpCircle+const NodeRenderer = memo(+ ({+ node,+ setCurrentNode,+ isSelected,+ onCheckboxChange,+ isNodeChecked,+ }: {+ node: any+ setCurrentNode: (node: NodeData) => void+ isSelected: any+ onCheckboxChange: (node: NodeData, checked: boolean) => void+ isNodeChecked: (nodeId: string) => boolean+ }) => {+ const handleClick = useCallback(() => setCurrentNode(node), [node, setCurrentNode])+ const handleCheckboxChange = useCallback(+ (checked: boolean) => {+ onCheckboxChange(node, checked)+ },+ [node, onCheckboxChange],+ )- const handleClick = useCallback(() => setCurrentNode(node), [node, setCurrentNode])+ if (node.data?.type === "social") {+ return (+ <SocialNode+ setCurrentNode={setCurrentNode}+ node={node}+ isSelected={isSelected}+ onCheckboxChange={onCheckboxChange}+ isNodeChecked={isNodeChecked}+ />+ )+ }- if (node.data?.type === "social") {- return <SocialNode- setCurrentNode={setCurrentNode}- node={node}- isSelected={isSelected}- />- }- return (- <Button- variant={"ghost"}- className={cn(- 'flex items-center justify-start p-4 !py-5 hover:bg-background rounded-none text-left border-b border-l-2 border-l-transparent',- isSelected(node.id) && 'border-l-primary bg-background'- )}- onClick={handleClick}- >- {/* <IconContainer+ return (+ <div className="flex items-center hover:bg-background border-b">+ <div className="pl-2">+ <Checkbox checked={isNodeChecked(node.id)} onCheckedChange={handleCheckboxChange} className="mr-1" />+ </div>+ <Button+ variant={"ghost"}+ className={cn(+ "flex-1 flex truncate items-center justify-start p-4 !py-5 rounded-none text-left border-l-2 border-l-transparent",+ isSelected(node.id) && "border-l-primary bg-background",+ )}+ onClick={handleClick}+ >+ {/* <IconContainertype={node?.data?.type}icon={Icon}size={12}/> */}- <div className='grow truncate text-ellipsis'>{node?.data?.label}</div>- <TypeBadge type={node?.data?.type} />- </Button>- )-})--const NodesPanel = memo(({ nodes, isLoading }: { nodes: NodeData[], isLoading?: boolean }) => {+ <div className="grow truncate text-ellipsis">{node?.data?.label}</div>+ <TypeBadge type={node?.data?.type} />+ </Button>+ </div>+ )+ },+)- const setCurrentNode = useSketchStore(state => state.setCurrentNode)- const isSelected = useSketchStore(state => state.isSelected)+const NodesPanel = memo(({ nodes, isLoading }: { nodes: NodeData[]; isLoading?: boolean }) => {+ const setCurrentNode = useSketchStore((state) => state.setCurrentNode)+ const isSelected = useSketchStore((state) => state.isSelected)+ const setSelectedNodes = useSketchStore((state) => state.setSelectedNodes)+ const selectedNodes = useSketchStore((state) => state.selectedNodes || [])const [searchQuery, setSearchQuery] = useState<string>("")const [filters, setFilters] = useState<null | string[]>(null) // 'individual', 'email', etc.+const filteredNodes = useMemo(() => {const searchText = searchQuery.toLowerCase()return nodes?.filter((node) => {const matchesSearch =//@ts-ignore- node?.data?.label?.toLowerCase().includes(searchText) ||- node?.id?.toLowerCase().includes(searchText)+ node?.data?.label?.toLowerCase().includes(searchText) || node?.id?.toLowerCase().includes(searchText)const matchesFilter = !filters || filters.includes(node?.data?.type as string)@@ -116,11 +165,9 @@ const NodesPanel = memo(({ nodes, isLoading }: { nodes: NodeData[], isLoading?:if (filter === null) {setFilters(null)} else {- setFilters(prev => {+ setFilters((prev) => {if (prev === null) return [filter]- const next = prev.includes(filter)- ? prev.filter(f => f !== filter)- : [...prev, filter]+ const next = prev.includes(filter) ? prev.filter((f) => f !== filter) : [...prev, filter]return next.length === 0 ? null : next})}@@ -134,11 +181,36 @@ const NodesPanel = memo(({ nodes, isLoading }: { nodes: NodeData[], isLoading?:setFilters(null)}, [])+ // Check if a node is in the selectedNodes array+ const isNodeChecked = useCallback(+ (nodeId: string) => {+ return selectedNodes.some((node) => node.id === nodeId)+ },+ [selectedNodes],+ )++ // Handle checkbox change+ const handleCheckboxChange = useCallback(+ (node: NodeData, checked: boolean) => {+ if (checked) {+ // Add node to selected nodes if not already there+ setSelectedNodes([...selectedNodes.filter((n) => n.id !== node.id), node])+ } else {+ // Remove node from selected nodes+ setSelectedNodes(selectedNodes.filter((n) => n.id !== node.id))+ }+ },+ [selectedNodes, setSelectedNodes],+ )+return (<div className="overflow-auto bg-card h-full flex flex-col w-full !p-0 !m-0"><div className="sticky border-b top-0 p-2 bg-card z-10"><div className="flex items-center gap-2">- <Badge className='h-7' variant={"outline"}><span className='font-semibold'>{nodes?.length || 0}</span> <span className='font-normal opacity-60'>nodes</span></Badge>+ <Badge className="h-7" variant={"outline"}>+ <span className="font-semibold">{nodes?.length || 0}</span>{" "}+ <span className="font-normal opacity-60">nodes</span>+ </Badge><div className="relative grow"><Search className="absolute left-2.5 top-1.5 h-4 w-4 text-muted-foreground" /><Input@@ -153,42 +225,67 @@ const NodesPanel = memo(({ nodes, isLoading }: { nodes: NodeData[], isLoading?:<div><DropdownMenuTrigger asChild><Button variant={"outline"} className="h-7 w-8 relative" size={"icon"}>- <FilterIcon className={cn("opacity-60 h-3 w-3", filters && 'opacity-100')} />- {filters && <Badge className='absolute -top-2 -right-1 text-xs rounded-full h-4 w-4' variant={"default"}>{filters.length}</Badge>}+ <FilterIcon className={cn("opacity-60 h-3 w-3", filters && "opacity-100")} />+ {filters && (+ <Badge className="absolute -top-2 -right-1 text-xs rounded-full h-4 w-4" variant={"default"}>+ {filters.length}+ </Badge>+ )}</Button></DropdownMenuTrigger></div><DropdownMenuContent className="w-48 max-h-[50vh] space-y-1 overflow-y-auto">- <DropdownMenuLabel>{filters ? <Badge variant={"outline"} className='flex items-center gap-1 pr-1'>{filters?.length} filter(s)<Button size={"icon"} variant={"ghost"} className='h-5 w-5 rounded-full' onClick={clearFilters}><XIcon className='h-3 w-3' /></Button></Badge> : "filters"}</DropdownMenuLabel>+ <DropdownMenuLabel>+ {filters ? (+ <Badge variant={"outline"} className="flex items-center gap-1 pr-1">+ {filters?.length} filter(s)+ <Button size={"icon"} variant={"ghost"} className="h-5 w-5 rounded-full" onClick={clearFilters}>+ <XIcon className="h-3 w-3" />+ </Button>+ </Badge>+ ) : (+ "filters"+ )}+ </DropdownMenuLabel><DropdownMenuSeparator />- <DropdownMenuItem className={cn(filters == null && "bg-primary")} onClick={() => toggleFilter(null)}>All</DropdownMenuItem>+ <DropdownMenuItem className={cn(filters == null && "bg-primary")} onClick={() => toggleFilter(null)}>+ All+ </DropdownMenuItem>{actionItems.map((item) => (- <DropdownMenuItem className={cn(filters?.includes(item?.type) && "bg-primary/30")} key={item.id} onClick={() => toggleFilter(item?.type)}>{item?.type || "unknown"}</DropdownMenuItem>+ <DropdownMenuItem+ className={cn(filters?.includes(item?.type) && "bg-primary/30")}+ key={item.id}+ onClick={() => toggleFilter(item?.type)}+ >+ {item?.type || "unknown"}+ </DropdownMenuItem>))}</DropdownMenuContent></DropdownMenu></div></div>- {isLoading && <div className='text-sm p-4 text-center'>- <Loader label="Loading..." />- </div>}+ {isLoading && (+ <div className="text-sm p-4 text-center">+ <Loader label="Loading..." />+ </div>+ )}{!isLoading && filteredNodes?.length === 0 && searchQuery === "" && (- <div className='text-sm p-4 text-center'>- <p className='border rounded-md border-dashed p-4 text-center'>+ <div className="text-sm p-4 text-center">+ <p className="border rounded-md border-dashed p-4 text-center">Right click on the panel to add your first investigation item.</p></div>)}{filteredNodes?.length === 0 && searchQuery ? (- <div className="p-4 text-center text-muted-foreground">- No nodes match your search- </div>+ <div className="p-4 text-center text-muted-foreground">No nodes match your search</div>) : (filteredNodes?.map((node: any) => (<NodeRenderernode={node}isSelected={isSelected}setCurrentNode={setCurrentNode}+ onCheckboxChange={handleCheckboxChange}+ isNodeChecked={isNodeChecked}key={node.id}/>))@@ -197,4 +294,4 @@ const NodesPanel = memo(({ nodes, isLoading }: { nodes: NodeData[], isLoading?:)})-export default NodesPanel\ No newline at end of file+export default NodesPaneldiff --git a/flowsint-web/src/components/transforms/scanner-node.tsx b/flowsint-web/src/components/transforms/scanner-node.tsxindex 1ad4a812..2e2a9102 100644--- a/flowsint-web/src/components/transforms/scanner-node.tsx+++ b/flowsint-web/src/components/transforms/scanner-node.tsx@@ -11,7 +11,7 @@ export interface ScannerNodeData extends Record<string, unknown> {name: stringmodule: stringdoc: string | null- category?: string+ category: stringtype: stringcolor?: stringinputs: {@@ -52,11 +52,11 @@ function areEqual(prevProps: ScannerNodeProps, nextProps: ScannerNodeProps) {// Memoized scanner node component with custom equality checkconst ScannerNode = memo(({ data, selected, isConnectable }: ScannerNodeProps) => {- const color = categoryColors[data.type] || "#94a3b8"+ const color = categoryColors[data?.category] || "#94a3b8"return (<BaseNodeSchemaclassName="shadow-md rounded-md !border-l-2 p-0 bg-background !max-w-[340px]"- style={{ borderLeftWidth: "8px", borderLeftColor: color || "#888", cursor: "grab" }}+ style={{ borderLeftWidth: "8px", borderLeftColor: color, cursor: "grab" }}selected={selected}><div className="p-3 bg-card rounded-t-md">diff --git a/flowsint-web/src/components/ui/base-node.tsx b/flowsint-web/src/components/ui/base-node.tsxindex eea7dd56..77864e25 100644--- a/flowsint-web/src/components/ui/base-node.tsx+++ b/flowsint-web/src/components/ui/base-node.tsx@@ -24,9 +24,10 @@ BaseNode.displayName = "BaseNode";export const BaseNodeSchema = forwardRef<HTMLDivElement,HTMLAttributes<HTMLDivElement> & { selected?: boolean }->(({ className, selected, ...props }, ref) => (+>(({ className, selected, style, ...props }, ref) => (<divref={ref}+ style={style}className={cn("relative rounded-md border bg-card p-5 text-card-foreground",className,diff --git a/flowsint-web/src/lib/action-items.ts b/flowsint-web/src/lib/action-items.tsindex e89895c0..8fd2b014 100644--- a/flowsint-web/src/lib/action-items.ts+++ b/flowsint-web/src/lib/action-items.ts@@ -533,4 +533,12 @@ export const actionItems: ActionItem[] = [},]-+export function findActionItemByKey(key: string): ActionItem | undefined {+ for (const item of actionItems) {+ if (item.key === key) return item+ if (item.children) {+ const found = item.children.find(child => child.key === key)+ if (found) return found+ }+ }+}\ No newline at end of filediff --git a/flowsint-web/src/lib/actions/sketches.ts b/flowsint-web/src/lib/actions/sketches.tsindex eab0c521..8cb0949d 100644--- a/flowsint-web/src/lib/actions/sketches.ts+++ b/flowsint-web/src/lib/actions/sketches.ts@@ -2,6 +2,7 @@import { createClient } from "../supabase/server"import { redirect } from "next/navigation"import { revalidatePath } from "next/cache"+import { NodeData } from "@/types"export async function createNewSketch(formData: FormData, investigation_id: string) {const supabase = await createClient()@@ -25,12 +26,12 @@ export async function createNewSketch(formData: FormData, investigation_id: stri}}-type Schema = {+type AddNodeSchema = {node: anysketch_id: string | string[]}-export async function saveNode(schema: Schema) {+export async function saveNode(schema: AddNodeSchema) {try {const { node, sketch_id } = schemaif (!sketch_id) {@@ -66,4 +67,53 @@ export async function saveNode(schema: Schema) {error: "Unexpected error during schema save"}}-}\ No newline at end of file+}+++type AddEdgeSchema = {+ source: NodeData,+ target: NodeData,+ type: string,+ label: string,+ sketch_id: string | string[]+}+++export const saveEdge = async (schema: AddEdgeSchema) => {+ const body = {+ source: schema.source,+ target: schema.target,+ type: schema.type,+ label: schema.label,+ };+ try {+ const { sketch_id } = schema+ if (!sketch_id) {+ return { success: false, error: "Missing sketch ID" }+ }+ const supabase = await createClient()+ await supabase.auth.refreshSession()+ const { data: { session } } = await supabase.auth.getSession();+ const jwt = session?.access_token;+ console.log(body)+ const res = await fetch(`${process.env.NEXT_PUBLIC_DOCKER_FLOWSINT_API}/sketch/${sketch_id}/relations/add`, {+ method: "POST",+ body: JSON.stringify(body),+ headers: {+ Authorization: `Bearer ${jwt}`,+ "Content-Type": "application/json",+ },+ });+ if (!res.ok) {+ throw Error("Failed to create new relation.")+ }+ const data = await res.json();+ return {+ success: true,+ data: data,+ timestamp: new Date().toISOString()+ }+ } catch (error) {+ throw Error("Failed to create new relation.")+ }+};diff --git a/flowsint-web/src/store/sketch-store.ts b/flowsint-web/src/store/sketch-store.tsindex e00fcf54..5a882927 100644--- a/flowsint-web/src/store/sketch-store.ts+++ b/flowsint-web/src/store/sketch-store.ts@@ -1,123 +1,113 @@"use client"import { create } from "zustand"-import { devtools } from "zustand/middleware"-import type { Sketch } from "@/types/sketch"import type { EdgeData, NodeData } from "@/types"-import { ActionItem, actionItems } from "@/lib/action-items"+import { ActionItem, actionItems, findActionItemByKey } from "@/lib/action-items"interface SketchState {- // Nodes data- nodes: NodeData[],- edges: EdgeData[],+ // === Graph ===+ nodes: NodeData[]+ edges: EdgeData[]+ setNodes: (nodes: NodeData[]) => void+ setEdges: (edges: EdgeData[]) => void+ addNode: (newNode: Partial<NodeData>) => NodeData++ // === Selection & Current ===currentNode: NodeData | nullselectedNodes: NodeData[]- // Nodes statesisCurrent: (nodeId: string) => booleanisSelected: (nodeId: string) => boolean- // Nodes setters- setNodes: (nodes: NodeData[]) => void- setEdges: (edges: EdgeData[]) => voidsetCurrentNode: (node: NodeData | null) => voidsetSelectedNodes: (nodes: NodeData[]) => voidclearSelectedNodes: () => voidtoggleNodeSelection: (node: NodeData, multiSelect?: boolean) => void- // Nodes mutators- addNode: (newNode: Partial<NodeData>) => void- // Main modal, showing different first categ items- openMainDialog: boolean,- setOpenMainDialog: (open: boolean) => void,- // Second modal, open after clicking on an item- openFormDialog: boolean,++ // === Dialogs ===+ openMainDialog: boolean+ openFormDialog: boolean+ openAddRelationDialog: boolean+ setOpenMainDialog: (open: boolean) => voidsetOpenFormDialog: (open: boolean) => void- // Open the form dialog with correct form proposed- handleOpenFormModal: (key: string) => void- // To know the selected node type for the form+ setOpenAddRelationDialog: (open: boolean) => void++ // === Action Type for Form ===currentNodeType: ActionItem | nullsetCurrentNodeType: (nodeType: ActionItem | null) => void- // filters- filters: Record<string, unknown>,+ handleOpenFormModal: (key: string) => void++ // === Filters ===+ filters: Record<string, unknown>setFilters: (filters: Record<string, unknown>) => void+}+export const useSketchStore = create<SketchState>()((set, get) => ({+ // === Graph ===+ nodes: [],+ edges: [],+ setNodes: (nodes) => set({ nodes }),+ setEdges: (edges) => set({ edges }),+ addNode: (newNode) => {+ const { nodes } = get()+ const nodeWithId: NodeData = {+ id: newNode.id || `node-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,+ ...newNode,+ } as NodeData+ set({ nodes: [...nodes, nodeWithId] })+ return nodeWithId+ },-}+ // === Selection & Current ===+ currentNode: null,+ selectedNodes: [],+ isCurrent: (nodeId) => get().currentNode?.id === nodeId,+ isSelected: (nodeId) => {+ const { selectedNodes, isCurrent } = get()+ return selectedNodes.some((node) => node.id === nodeId) || isCurrent(nodeId)+ },+ setCurrentNode: (node) => set({ currentNode: node }),+ setSelectedNodes: (nodes) => set({ selectedNodes: nodes }),+ clearSelectedNodes: () => set({ selectedNodes: [], currentNode: null }),+ toggleNodeSelection: (node, multiSelect = false) => {+ const { selectedNodes, currentNode } = get()+ const isSelected = selectedNodes.some((n) => n.id === node.id)+ let newSelected: NodeData[]++ if (multiSelect) {+ newSelected = isSelected+ ? selectedNodes.filter((n) => n.id !== node.id)+ : [...selectedNodes, node]+ } else {+ newSelected = isSelected && selectedNodes.length === 1 ? [] : [node]+ }++ set({+ selectedNodes: newSelected,+ currentNode: multiSelect ? currentNode : (isSelected ? null : node),+ })+ },-export const useSketchStore = create<SketchState>()(+ // === Dialogs ===+ openMainDialog: false,+ openFormDialog: false,+ openAddRelationDialog: false,+ setOpenMainDialog: (open) => set({ openMainDialog: open }),+ setOpenFormDialog: (open) => set({ openFormDialog: open }),+ setOpenAddRelationDialog: (open) => set({ openAddRelationDialog: open }),- (set, get) => ({- nodes: [],- edges: [],- currentNode: null,- selectedNodes: [],- openMainDialog: false,- openFormDialog: false,- currentNodeType: null,- isCurrent: (nodeId) => {- const { currentNode } = get()- return currentNode !== null && currentNode.id === nodeId- },- isSelected: (nodeId) => {- const { selectedNodes, isCurrent } = get()- return selectedNodes.some((node) => node.id === nodeId) || isCurrent(nodeId)- },- setNodes: (nodes) => set({ nodes }),- setEdges: (edges) => set({ edges }),- setCurrentNode: (node) => {- set({ currentNode: node })- },- setSelectedNodes: (nodes) => {- set({ selectedNodes: nodes })- },- clearSelectedNodes: () => {- set({ selectedNodes: [], currentNode: null })- },- addNode: (newNode) => {- const { nodes } = get()- const nodeWithId = {- id: newNode.id || `node-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,- ...newNode,- } as NodeData+ // === Action Type for Form ===+ currentNodeType: null,+ setCurrentNodeType: (nodeType) => set({ currentNodeType: nodeType }),+ handleOpenFormModal: (key) => {+ const selectedItem = findActionItemByKey(key)+ if (!selectedItem) return+ set({+ currentNodeType: selectedItem,+ openMainDialog: false,+ openFormDialog: true,+ })+ },- const newNodes = [...nodes, nodeWithId]- set({ nodes: newNodes })- return nodeWithId- },- toggleNodeSelection: (node, multiSelect = false) => {- const { selectedNodes } = get()- const isSelected = selectedNodes.some((n) => n.id === node.id)- if (multiSelect) {- if (isSelected) {- set({ selectedNodes: selectedNodes.filter((n) => n.id !== node.id) })- } else {- set({ selectedNodes: [...selectedNodes, node] })- }- } else {- if (isSelected && selectedNodes.length === 1) {- set({ selectedNodes: [] })- } else {- set({ selectedNodes: [node] })- }- }- set({ currentNode: isSelected ? null : node })- },- setOpenMainDialog: (open) => set({ openMainDialog: open }),- setOpenFormDialog: (open) => set({ openFormDialog: open }),- setCurrentNodeType: (nodeType) => set({ currentNodeType: nodeType }),- handleOpenFormModal: (key) => {- const selectedItem = actionItems.find(item => item.key === key) ||- actionItems- .filter(item => item.children)- .flatMap(item => item.children || [])- .find(item => item.key === key)- if (!selectedItem) {- return- }- set({- currentNodeType: selectedItem,- openMainDialog: false,- openFormDialog: true- })- },- filters: {},- setFilters: (filters) => set({ filters }),- }))\ No newline at end of file+ // === Filters ===+ filters: {},+ setFilters: (filters) => set({ filters }),+}))