A modern platform for visual, flexible, and extensible graph-based investigations. For cybersecurity analysts and investigators.
fix(frontend): type the sketch-service API boundary
dextmorgn639648a882d4
diff --git a/flowsint-app/src/api/api.ts b/flowsint-app/src/api/api.tsindex afa8bb63..03be5455 100644--- a/flowsint-app/src/api/api.ts+++ b/flowsint-app/src/api/api.ts@@ -2,6 +2,10 @@ import { useAuthStore } from '@/stores/auth-store'const API_URL = import.meta.env.VITE_API_URL ?? ''+// Return type is genuinely per-endpoint — every sketchService/flowService/...+// caller declares its own real return type and relies on this resolving+// structurally against it. A generic here would need an explicit type+// argument at every call site across the whole app for no real gain.export async function fetchWithAuth(endpoint: string, options: RequestInit = {}): Promise<any> {const token = useAuthStore.getState().tokendiff --git a/flowsint-app/src/api/sketch-service.ts b/flowsint-app/src/api/sketch-service.tsindex 7026fb40..8a9eea46 100644--- a/flowsint-app/src/api/sketch-service.ts+++ b/flowsint-app/src/api/sketch-service.ts@@ -1,97 +1,122 @@import { fetchWithAuth } from './api'+import type {+ Sketch,+ SketchGraphData,+ DetectionResult,+ EntityMapping,+ PreviewEdge,+ ImportAnalysisResult,+ ImportExecutionResult,+ RelationshipType+} from '@/types'+import type { GraphNode } from '@/types/graph'+import type { ActionItem } from '@/lib/action-items'++// `inline=true` asks the backend for the relationships-already-joined+// shape (used by the flat table view) instead of the default {nds, rls}+// graph slice — the response shape genuinely depends on that flag, hence+// the overload rather than a single loosely-typed union return.+async function getGraphDataById(sketchId: string, inline: true): Promise<RelationshipType[]>+async function getGraphDataById(sketchId: string, inline?: false): Promise<SketchGraphData>+async function getGraphDataById(+ sketchId: string,+ inline: boolean = false+): Promise<SketchGraphData | RelationshipType[]> {+ return fetchWithAuth(`/api/sketches/${sketchId}/graph?format=${inline ? 'inline' : ''}`, {+ method: 'GET'+ })+}export const sketchService = {- get: async (): Promise<any> => {+ get: async (): Promise<Sketch[]> => {return fetchWithAuth('/api/sketches', {method: 'GET'})},- getById: async (sketchId: string): Promise<any> => {+ getById: async (sketchId: string): Promise<Sketch> => {return fetchWithAuth(`/api/sketches/${sketchId}`, {method: 'GET'})},- getGraphDataById: async (sketchId: string, inline: boolean = false): Promise<any> => {- return fetchWithAuth(`/api/sketches/${sketchId}/graph?format=${inline ? 'inline' : ''}`, {- method: 'GET'- })- },- create: async (body: BodyInit): Promise<any> => {+ getGraphDataById,+ // Backend returns the created sketch on success, or an { error } payload+ // instead of a 4xx/5xx status on failure — callers branch on `id`.+ create: async (body: BodyInit): Promise<Sketch | { error: string }> => {return fetchWithAuth(`/api/sketches/create`, {method: 'POST',body: body})},- delete: async (sketchId: string): Promise<any> => {+ delete: async (sketchId: string): Promise<unknown> => {return fetchWithAuth(`/api/sketches/${sketchId}`, {method: 'DELETE'})},- addNode: async (sketchId: string, body: BodyInit): Promise<any> => {+ addNode: async (sketchId: string, body: BodyInit): Promise<{ node: GraphNode }> => {return fetchWithAuth(`/api/sketches/${sketchId}/nodes/add`, {method: 'POST',body: body})},- addEdge: async (sketchId: string, body: BodyInit): Promise<any> => {+ addEdge: async (sketchId: string, body: BodyInit): Promise<unknown> => {return fetchWithAuth(`/api/sketches/${sketchId}/relations/add`, {method: 'POST',body: body})},- mergeNodes: async (sketchId: string, body: BodyInit): Promise<any> => {+ mergeNodes: async (sketchId: string, body: BodyInit): Promise<unknown> => {return fetchWithAuth(`/api/sketches/${sketchId}/nodes/merge`, {method: 'POST',body: body})},- deleteNodes: async (sketchId: string, body: BodyInit): Promise<any> => {+ deleteNodes: async (sketchId: string, body: BodyInit): Promise<unknown> => {return fetchWithAuth(`/api/sketches/${sketchId}/nodes`, {method: 'DELETE',body: body})},- deleteEdges: async (sketchId: string, body: BodyInit): Promise<any> => {+ deleteEdges: async (sketchId: string, body: BodyInit): Promise<unknown> => {return fetchWithAuth(`/api/sketches/${sketchId}/relationships`, {method: 'DELETE',body: body})},- updateNode: async (sketchId: string, body: BodyInit): Promise<any> => {+ updateNode: async (sketchId: string, body: BodyInit): Promise<{ status: string }> => {return fetchWithAuth(`/api/sketches/${sketchId}/nodes/edit`, {method: 'PUT',body: body})},- updateEdge: async (sketchId: string, body: BodyInit): Promise<any> => {+ updateEdge: async (sketchId: string, body: BodyInit): Promise<unknown> => {return fetchWithAuth(`/api/sketches/${sketchId}/relationships/edit`, {method: 'PUT',body: body})},- getNodeNeighbors: async (sketchId: string, nodeId: string): Promise<any> => {+ getNodeNeighbors: async (sketchId: string, nodeId: string): Promise<SketchGraphData> => {return fetchWithAuth(`/api/sketches/${sketchId}/nodes/${nodeId}`, {method: 'GET'})},- types: async (): Promise<any> => {+ types: async (): Promise<ActionItem[]> => {return fetchWithAuth(`/api/types`, {method: 'GET'})},- detectType: async (text: string): Promise<any> => {+ detectType: async (text: string): Promise<DetectionResult> => {return fetchWithAuth(`/api/types/detect`, {method: 'POST',body: JSON.stringify({ text })})},- update: async (sketchId: string, body: BodyInit): Promise<any> => {+ update: async (sketchId: string, body: BodyInit): Promise<Sketch> => {return fetchWithAuth(`/api/sketches/${sketchId}`, {method: 'PUT',body: body})},- analyzeImportFile: async (sketchId: string, file: File): Promise<any> => {+ analyzeImportFile: async (sketchId: string, file: File): Promise<ImportAnalysisResult> => {const formData = new FormData()formData.append('file', file)@@ -102,16 +127,9 @@ export const sketchService = {},executeImport: async (sketchId: string,- entityMappings: Array<{- id: string- entity_type: string- include: boolean- nodeLabel: string- node_id?: string- data: Record<string, any>- }>,- edges: any- ): Promise<any> => {+ entityMappings: EntityMapping[],+ edges: PreviewEdge[]+ ): Promise<ImportExecutionResult> => {const formData = new FormData()formData.append('entity_mappings_json', JSON.stringify({ nodes: entityMappings, edges: edges }))@@ -123,13 +141,13 @@ export const sketchService = {updateNodePositions: async (sketchId: string,positions: Array<{ nodeId: string; x: number; y: number }>- ): Promise<any> => {+ ): Promise<unknown> => {return fetchWithAuth(`/api/sketches/${sketchId}/nodes/positions`, {method: 'PUT',body: JSON.stringify({ positions })})},- exportSketch: async (sketchId: string, format: 'json' = 'json'): Promise<any> => {+ exportSketch: async (sketchId: string, format: 'json' = 'json'): Promise<unknown> => {const response = await fetchWithAuth(`/api/sketches/${sketchId}/export?format=${format}`, {method: 'GET'})diff --git a/flowsint-app/src/components/sketches/details-panel/neighbors.tsx b/flowsint-app/src/components/sketches/details-panel/neighbors.tsxindex c4583818..9995efbb 100644--- a/flowsint-app/src/components/sketches/details-panel/neighbors.tsx+++ b/flowsint-app/src/components/sketches/details-panel/neighbors.tsx@@ -29,18 +29,26 @@ const NeighborsGraph = memo(queryFn: () => sketchService.getNodeNeighbors(sketchId, currentNode.id)})- // omit x and y positions to let the GraphViewer manange the forces- const nodes = useMemo(+ // omit x and y positions to let the GraphViewer manage the forces —+ // the rest of GraphNode's fields aren't used by this mini preview+ // graph, so they're filled with the same defaults new nodes get.+ const nodes = useMemo<GraphNode[] | undefined>(() =>neighborsData?.nds.map(- ({ id, nodeType, nodeColor, nodeIcon, nodeLabel, nodeImage, nodeShape }: GraphNode) => ({+ ({ id, nodeType, nodeColor, nodeIcon, nodeLabel, nodeImage, nodeShape }) => ({id,nodeType,nodeColor,nodeIcon,nodeLabel,nodeImage,- nodeShape+ nodeShape,+ nodeProperties: {},+ nodeMetadata: {},+ nodeSize: 4,+ nodeFlag: null,+ x: 0,+ y: 0})),[neighborsData?.nds]@@ -57,7 +65,7 @@ const NeighborsGraph = memo()return (<div ref={containerRef} className="overflow-hidden bg-background relative h-full w-full">- {isLoading ? (+ {isLoading || !neighborsData || !nodes ? (<div className="flex items-center justify-center grow h-full"><Loader /></div>diff --git a/flowsint-app/src/components/sketches/graph/hooks/use-quick-add.ts b/flowsint-app/src/components/sketches/graph/hooks/use-quick-add.tsindex 8873f505..5a76b8d0 100644--- a/flowsint-app/src/components/sketches/graph/hooks/use-quick-add.ts+++ b/flowsint-app/src/components/sketches/graph/hooks/use-quick-add.ts@@ -2,23 +2,11 @@ import { useCallback, useEffect, useState } from 'react'import { useGraphStore } from '@/stores/graph-store'import { sketchService } from '@/api/sketch-service'import { type GraphNode, type NodeProperties } from '@/types/graph'+import { type DetectionResult } from '@/types/sketch'import { useDebounce } from '@/hooks/use-debounce'import { toast } from 'sonner'import { v4 as uuidv4 } from 'uuid'-interface DetectionResult {- type: string- key: string- fields: Array<{- name: string- label: string- description: string- required: boolean- primary: boolean- value: string | null- }>-}-interface QuickAddState {active: booleanposition: { x: number; y: number } | null // screen coordsdiff --git a/flowsint-app/src/components/sketches/import-preview.tsx b/flowsint-app/src/components/sketches/import-preview.tsxindex b14accda..8aca0d3e 100644--- a/flowsint-app/src/components/sketches/import-preview.tsx+++ b/flowsint-app/src/components/sketches/import-preview.tsx@@ -18,18 +18,15 @@ import { useActionItems } from '@/hooks/use-action-items'import { toast } from 'sonner'import { useGraphControls } from '@/stores/graph-controls-store'import { v4 as uuidv4 } from 'uuid'--interface EntityMapping {- id: string- entity_type: string- include: boolean- nodeLabel: string- node_id?: string- data: Record<string, any>-}+import type {+ EntityMapping,+ ImportAnalysisResult,+ ImportExecutionResult,+ PreviewEdge+} from '@/types'interface ImportPreviewProps {- analysisResult: any+ analysisResult: ImportAnalysisResultsketchId: stringonSuccess: () => voidonCancel: () => void@@ -180,7 +177,7 @@ const EntityRow = memo(<div key={field} className="px-3 py-2 border-r w-[200px] shrink-0"><DebouncedInputclassName="h-8 w-full text-xs"- value={mapping.data[field] || ''}+ value={String(mapping.data[field] ?? '')}onChange={(value) => onFieldChange(mapping.id, field, value)}disabled={!mapping.include}placeholder="-"@@ -368,14 +365,10 @@ export function ImportPreview({actionItems.forEach((item) => {if (item.children) {item.children.forEach((child) => {- fields[child.label] = child.fields- .filter((f: any) => f.name !== 'label')- .map((f: any) => f.name)+ fields[child.label] = child.fields.filter((f) => f.name !== 'label').map((f) => f.name)})} else if (item.fields) {- fields[item.label] = item.fields- .filter((f: any) => f.name !== 'label')- .map((f: any) => f.name)+ fields[item.label] = item.fields.filter((f) => f.name !== 'label').map((f) => f.name)}})@@ -394,12 +387,12 @@ export function ImportPreview({const newMappingsById = new Map<string, EntityMapping>()const newMappingIdsByType: Record<string, string[]> = {}- Object.entries(analysisResult.entities).forEach(([typeName, group]: [string, any]) => {+ Object.entries(analysisResult.entities).forEach(([typeName, group]) => {const typeFields = fieldsByType[typeName] || []const ids: string[] = []- group.results.forEach((entity: any) => {- const data: Record<string, any> = {}+ group.results.forEach((entity) => {+ const data: Record<string, unknown> = {}typeFields.forEach((field) => {data[field] = entity.obj[field] ?? ''})@@ -455,14 +448,14 @@ export function ImportPreview({}, [])const [isImporting, setIsImporting] = useState(false)- const [importResult, setImportResult] = useState<any>(null)+ const [importResult, setImportResult] = useState<ImportExecutionResult | null>(null)const entityTypes = useMemo(() => {if (!actionItems) return []const types: string[] = []actionItems.forEach((item) => {if (item.children) {- item.children.forEach((c: any) => c.label && types.push(c.label))+ item.children.forEach((c) => c.label && types.push(c.label))} else if (item.label) {types.push(item.label)}@@ -487,7 +480,7 @@ export function ImportPreview({if (!mapping || mapping.entity_type === newType) return prevconst newFields = fieldsByType[newType] || []- const newData: Record<string, any> = {}+ const newData: Record<string, unknown> = {}newFields.forEach((field) => {newData[field] = mapping.data[field] ?? ''})@@ -725,13 +718,6 @@ export function ImportPreview({)}-type PreviewEdge = {- from_id: string- to_id: string- from_obj: { label: string }- to_obj: { label: string }- label: string-}type EdgesPanelProps = {edges: PreviewEdge[]}diff --git a/flowsint-app/src/components/sketches/new-sketch.tsx b/flowsint-app/src/components/sketches/new-sketch.tsxindex 980aa4fc..d9405498 100644--- a/flowsint-app/src/components/sketches/new-sketch.tsx+++ b/flowsint-app/src/components/sketches/new-sketch.tsx@@ -44,7 +44,7 @@ export default function NewSketch({ children }: NewSketchProps) {const createSketchMutation = useMutation({mutationFn: sketchService.create,onSuccess: (result) => {- if (result.id) {+ if ('id' in result && result.id) {toast.success('New sketch created.')router.navigate({to: `/dashboard/investigations/${investigationId}/graph/${result.id}`@@ -61,7 +61,7 @@ export default function NewSketch({ children }: NewSketchProps) {}if (sketchId) setOpen(false)} else {- toast.error(result.error || 'Failed to create sketch.')+ toast.error(('error' in result && result.error) || 'Failed to create sketch.')}},onError: (error) => {diff --git a/flowsint-app/src/types/sketch.ts b/flowsint-app/src/types/sketch.tsindex 04e53803..2b85f48d 100644--- a/flowsint-app/src/types/sketch.ts+++ b/flowsint-app/src/types/sketch.ts@@ -1,5 +1,6 @@import { type Profile } from './profile'import { type Investigation } from './investigation'+import { type GraphNode, type GraphEdge } from './graph'export interface Sketch {id: string@@ -11,9 +12,65 @@ export interface Sketch {last_updated_at: stringowner: Profileowner_id: string- relations?: any[]- individuals?: any[]+ relations?: unknown[]+ individuals?: unknown[]investigation?: Investigationinvestigation_id: stringmembers?: { profile: Profile }[]}++// Response shape shared by every sketch-service endpoint that returns a+// graph slice (full sketch graph, or a single node's neighbors).+export interface SketchGraphData {+ nds: GraphNode[]+ rls: GraphEdge[]+}++export interface DetectionResult {+ type: string+ key: string+ fields: Array<{+ name: string+ label: string+ description: string+ required: boolean+ primary: boolean+ value: string | null+ }>+}++// One row of the import-preview mapping table: a detected entity the user+// can include/exclude and relabel before it's persisted as a node.+export interface EntityMapping {+ id: string+ entity_type: string+ include: boolean+ nodeLabel: string+ node_id?: string+ data: Record<string, unknown>+}++export interface PreviewEntity {+ detected_type: string+ node_id?: string | number+ obj: Record<string, unknown> & { nodeLabel: string }+}++export interface PreviewEdge {+ from_id: string+ to_id: string+ from_obj: { label: string }+ to_obj: { label: string }+ label: string+}++export interface ImportAnalysisResult {+ entities: Record<string, { results: PreviewEntity[] }>+ edges: PreviewEdge[]+}++export interface ImportExecutionResult {+ status: string+ nodes_created: number+ errors: string[]+}