From d431ef4fae44b54fdfa9aef48576569d6c2f445a Mon Sep 17 00:00:00 2001 From: dextmorgn <64375473+dextmorgn@users.noreply.github.com> Date: Fri, 15 May 2026 18:55:25 +0200 Subject: [PATCH] docs: sync with flowsint-types and flowsint-enrichers (v1.2.8) - available-enrichers.mdx: add 17 missing enrichers, drop phantom entries - managing-enrichers.mdx: fix stale Troubleshooting referencing EnricherRegistry.register() - managing-types.mdx: note 8 registered-but-uncategorized types - bump all frontmatter to version 1.2.8 / 2026-05-15 --- docs/developers/getting-started.mdx | 18 + docs/developers/graph-format.mdx | 244 +++++ docs/developers/managing-enrichers.mdx | 715 ++++++++++++++ docs/developers/managing-tools.mdx | 512 ++++++++++ docs/developers/managing-types.mdx | 1253 ++++++++++++++++++++++++ docs/getting-started/enrichers.mdx | 53 + docs/getting-started/flows.mdx | 159 +++ docs/getting-started/quickstart.mdx | 42 + docs/getting-started/vault.mdx | 58 ++ docs/overview.mdx | 59 ++ docs/sources/available-enrichers.mdx | 163 +++ docs/syllabus.mdx | 73 ++ 12 files changed, 3349 insertions(+) create mode 100644 docs/developers/getting-started.mdx create mode 100644 docs/developers/graph-format.mdx create mode 100644 docs/developers/managing-enrichers.mdx create mode 100644 docs/developers/managing-tools.mdx create mode 100644 docs/developers/managing-types.mdx create mode 100644 docs/getting-started/enrichers.mdx create mode 100644 docs/getting-started/flows.mdx create mode 100644 docs/getting-started/quickstart.mdx create mode 100644 docs/getting-started/vault.mdx create mode 100644 docs/overview.mdx create mode 100644 docs/sources/available-enrichers.mdx create mode 100644 docs/syllabus.mdx diff --git a/docs/developers/getting-started.mdx b/docs/developers/getting-started.mdx new file mode 100644 index 0000000..ef3cde2 --- /dev/null +++ b/docs/developers/getting-started.mdx @@ -0,0 +1,18 @@ +--- +title: "Getting started" +description: "This guide explains how you can contribute to Flowsint." +category: "Developers" +order: 7 +author: "Flowsint Team" +tags: ["tutorial", "developers", "getting-started"] +version: "1.2.8" +last_updated_at: "2026-05-15" +--- + +## Contributing + +Your contribution to Flowsint is highly encouraged ! + +You can create your own [Types](/docs/developers/managing-types), [Tools](/docs/developers/managing-tools), [Enrichers](/docs/developers/managing-enrichers) and Flows, and sharing them by proposing [pull requests](https://github.com/reconurge/flowsint/pulls). + +Before diving in, you may also want to understand the [Graph format](/docs/developers/graph-format) to learn how nodes and edges are structured in the frontend visualization. diff --git a/docs/developers/graph-format.mdx b/docs/developers/graph-format.mdx new file mode 100644 index 0000000..5302ec4 --- /dev/null +++ b/docs/developers/graph-format.mdx @@ -0,0 +1,244 @@ +--- +title: "Graph format" +description: "Reference for the GraphNode and GraphEdge types used to represent entities and relationships in the Flowsint graph. Understanding these structures is essential for working with the frontend visualization and the graph database layer." +category: "Developers" +order: 11 +author: "Flowsint Team" +tags: ["tutorial", "developers", "graph", "nodes", "edges"] +version: "1.2.8" +last_updated_at: "2026-05-15" +--- + +## Overview + +Flowsint's graph visualization is built on two core data structures: **GraphNode** (representing entities) and **GraphEdge** (representing relationships between entities). These types are defined in `flowsint-app/src/types/graph.ts` and are used throughout the frontend for rendering, interaction, and data management. + +Understanding these structures is important when: +- Building enrichers that create nodes and relationships +- Working on the frontend visualization +- Debugging graph rendering issues +- Extending the graph with new visual features + +## GraphNode + +A `GraphNode` represents a single entity in the graph (e.g., a domain, an IP address, a person). Every node created by an enricher's `create_node()` method ends up as a `GraphNode` in the frontend. + +```typescript +type GraphNode = { + id: string + nodeType: string + nodeLabel: string + nodeProperties: NodeProperties + nodeSize: number + nodeColor: string | null + nodeIcon: keyof typeof LucideIcons | null + nodeImage: string | null + nodeFlag: flagColor | null + nodeShape: NodeShape | null + nodeMetadata: NodeMetadata + x: number + y: number + val?: number + neighbors?: any[] + links?: any[] +} +``` + +### Field reference + +| Field | Type | Description | +|-------|------|-------------| +| `id` | `string` | Unique identifier for the node. Derived from the type's primary field value. | +| `nodeType` | `string` | The entity type (e.g., `"Domain"`, `"Ip"`, `"Email"`). Maps to the Pydantic type class name. | +| `nodeLabel` | `string` | Human-readable label displayed on the node. Set by the type's `compute_label()` method. | +| `nodeProperties` | `NodeProperties` | All properties of the entity as key-value pairs. Contains the serialized fields from the Pydantic type. | +| `nodeSize` | `number` | Visual size of the node in the graph. | +| `nodeColor` | `string \| null` | Custom color override for the node (CSS color string), or `null` for default. | +| `nodeIcon` | `keyof LucideIcons \| null` | Icon to display on the node, from the [Lucide icon set](https://lucide.dev/icons/), or `null` for default. | +| `nodeImage` | `string \| null` | URL to an image to display on the node (e.g., a profile picture), or `null`. | +| `nodeFlag` | `flagColor \| null` | Color flag for visual tagging (see Flag colors below), or `null`. | +| `nodeShape` | `NodeShape \| null` | Shape of the node (see Node shapes below), or `null` for default circle. | +| `nodeMetadata` | `NodeMetadata` | Additional metadata as key-value pairs. Used for internal tracking and extended features. | +| `x` | `number` | X coordinate position in the graph canvas. | +| `y` | `number` | Y coordinate position in the graph canvas. | +| `val` | `number` (optional) | Value used by the force-graph engine for sizing calculations. | +| `neighbors` | `any[]` (optional) | Adjacent nodes, populated by the graph engine at runtime. | +| `links` | `any[]` (optional) | Connected edges, populated by the graph engine at runtime. | + +### NodeProperties + +```typescript +type NodeProperties = { + [key: string]: any +} +``` + +A flexible key-value object containing all the entity's properties. When a Pydantic type is serialized into a node, its fields become entries in `nodeProperties`. For example, a `Domain` node would have `nodeProperties.domain`, `nodeProperties.root`, etc. + +### NodeMetadata + +```typescript +type NodeMetadata = { + [key: string]: any +} +``` + +Similar to `nodeProperties` but used for system-level metadata rather than entity data. This can include information like creation timestamps, source enricher, or other tracking data. + +### Node shapes + +Nodes can be rendered in four shapes: + +```typescript +type NodeShape = 'circle' | 'square' | 'hexagon' | 'triangle' +``` + +| Shape | Use case | +|-------|----------| +| `circle` | Default shape for most entity types | +| `square` | Often used for infrastructure entities | +| `hexagon` | Used for grouped or aggregate entities | +| `triangle` | Used for alert or warning-related entities | + +### Flag colors + +Flags provide a visual tagging system for nodes. Users can flag nodes to highlight them during an investigation. + +```typescript +type flagColor = 'red' | 'orange' | 'blue' | 'green' | 'yellow' +``` + +Each flag color maps to specific Tailwind CSS classes for consistent styling: + +| Flag | Style | +|------|-------| +| `red` | `text-red-400 fill-red-200` | +| `orange` | `text-orange-400 fill-orange-200` | +| `blue` | `text-blue-400 fill-blue-200` | +| `green` | `text-green-400 fill-green-200` | +| `yellow` | `text-yellow-400 fill-yellow-200` | + +## GraphEdge + +A `GraphEdge` represents a relationship between two nodes (e.g., "RESOLVES_TO", "HAS_SUBDOMAIN", "FOUND_IN_BREACH"). Every relationship created by an enricher's `create_relationship()` method ends up as a `GraphEdge` in the frontend. + +```typescript +type GraphEdge = { + source: GraphNode['id'] + target: GraphNode['id'] + date?: string + id: string + label: string + caption?: string + type?: string + weight?: number + confidence_level?: number | string +} +``` + +### Field reference + +| Field | Type | Description | +|-------|------|-------------| +| `source` | `string` | ID of the source node (the "from" node in the relationship). | +| `target` | `string` | ID of the target node (the "to" node in the relationship). | +| `id` | `string` | Unique identifier for this edge. | +| `label` | `string` | Display label for the edge (e.g., `"RESOLVES_TO"`, `"HAS_EMAIL"`). This is the relationship type string passed to `create_relationship()`. | +| `date` | `string` (optional) | Timestamp associated with the relationship (ISO 8601 format). | +| `caption` | `string` (optional) | Additional descriptive text displayed on or near the edge. | +| `type` | `string` (optional) | Relationship classification type for filtering or styling. | +| `weight` | `number` (optional) | Numerical weight of the relationship, can be used for visual thickness or importance ranking. | +| `confidence_level` | `number \| string` (optional) | Confidence score for the relationship, indicating how reliable the connection is. | + +## How enrichers map to the graph + +When you write an enricher and call graph methods in `postprocess()`, here's how the data flows: + +### Creating nodes + +```python +# In your enricher's postprocess method +self.create_node(domain) # domain is a Pydantic Domain object +``` + +The graph service automatically: +1. Extracts the **type name** from the Pydantic class (e.g., `"Domain"`) -> `nodeType` +2. Reads the **primary field** value (e.g., `domain.domain`) -> used for `id` +3. Reads the **nodeLabel** field (set by `compute_label()`) -> `nodeLabel` +4. Serializes all fields into `nodeProperties` +5. Sets defaults for visual properties (`nodeSize`, `nodeColor`, etc.) + +### Creating relationships + +```python +# In your enricher's postprocess method +self.create_relationship(domain, ip, "RESOLVES_TO") +``` + +The graph service automatically: +1. Identifies the **source node** from `domain`'s type and primary field -> `source` +2. Identifies the **target node** from `ip`'s type and primary field -> `target` +3. Uses the relationship label `"RESOLVES_TO"` -> `label` +4. Generates a unique `id` for the edge + +### Relationship naming conventions + +Relationship labels follow these conventions: +- Use **UPPER_SNAKE_CASE** (e.g., `"RESOLVES_TO"`, `"HAS_SUBDOMAIN"`) +- Use **verb phrases** that describe the relationship direction (source -> target) +- The default relationship label is `"IS_RELATED_TO"` if none is specified +- Common patterns: + - `HAS_*` for ownership/containment (e.g., `"HAS_EMAIL"`, `"HAS_SUBDOMAIN"`) + - `RESOLVES_TO` for DNS-type lookups + - `FOUND_IN_*` for breach/leak associations + - `REGISTERED_BY` for WHOIS data + +## Graph settings + +The graph visualization is configurable through settings types: + +### ForceGraphSetting + +Controls the physics simulation of the force-directed graph layout: + +```typescript +type ForceGraphSetting = { + value: any + min?: number + max?: number + step?: number + type?: string + description?: string +} +``` + +### ExtendedSetting + +General-purpose settings with richer type information: + +```typescript +type ExtendedSetting = { + value: any + type: string + min?: number + max?: number + step?: number + options?: { value: string; label: string }[] + description?: string +} +``` + +These settings allow users to customize graph behavior like node repulsion, link distance, simulation speed, and visual preferences. + +## Reserved properties + +When creating nodes, certain property names are reserved by the system and should not be used as field names in your custom types: + +- `id` - Node identifier +- `x`, `y` - Position coordinates +- `nodeLabel` - Display label (set by `compute_label()`) +- `label` - Legacy label field +- `nodeType`, `type` - Entity type identifiers +- `nodeImage`, `nodeIcon`, `nodeColor`, `nodeSize` - Visual properties +- `created_at` - Creation timestamp +- `sketch_id` - Investigation sketch association diff --git a/docs/developers/managing-enrichers.mdx b/docs/developers/managing-enrichers.mdx new file mode 100644 index 0000000..dba3dff --- /dev/null +++ b/docs/developers/managing-enrichers.mdx @@ -0,0 +1,715 @@ +--- +title: "Managing enrichers" +description: "Quick start guide to creating Enricher for your OSINT investigations." +category: "Developers" +order: 10 +author: "Flowsint Team" +tags: ["tutorial", "developers", "creating-a-new-enricher"] +version: "1.2.8" +last_updated_at: "2026-05-15" +--- + +## Understanding Enrichers + +Enrichers are the high-level business logic layer in Flowsint. While types define data structures and tools wrap external utilities, enrichers orchestrate the entire intelligence gathering workflow. An enricher takes input data of one type, processes it through various tools or APIs, validates and enriches the results, creates graph database nodes and relationships, and returns structured output. + +Every enricher in Flowsint follows a two-phase execution model. The scan phase contains the core enriching logic where tools are executed, APIs are called, and data is gathered. Then, the postprocessing phase creates Neo4j graph nodes and relationships while returning the processed results. Input validation and normalization happens automatically through Pydantic type validation. + +Enrichers differ from tools in several fundamental ways. Tools are low-level wrappers that return raw data without knowledge of the Flowsint ecosystem. Enrichers are high-level workflows that understand types, create graph nodes, handle parameters, and orchestrate multiple tools. When you want to add a new data source, you create a tool. When you want to add a new intelligence workflow, you create an enricher. + +## Enricher architecture + +The enricher system is built around an abstract base class that defines the interface and execution flow. Every enricher you create inherits from this base class and implements specific methods. + +### The Enricher base class + +The base class lives at `flowsint-core/src/flowsint_core/core/enricher_base.py` and provides the framework for all enrichers. Here's what a minimal enricher looks like: + +```python +from typing import List +from flowsint_core.core.enricher_base import Enricher +from flowsint_enrichers.registry import flowsint_enricher +from flowsint_types import Domain, Ip + +@flowsint_enricher +class MyEnricher(Enricher): + """Description of what this enricher does.""" + + # Define input and output types as base types (not lists) + InputType = Domain + OutputType = Ip + + @classmethod + def name(cls) -> str: + """Unique identifier for this enricher.""" + return "domain_to_ip" + + @classmethod + def category(cls) -> str: + """Category this enricher belongs to.""" + return "Domain" + + @classmethod + def key(cls) -> str: + """Primary key field name for this enricher.""" + return "domain" + + async def scan(self, data: List[InputType]) -> List[OutputType]: + """Core enriching logic.""" + pass + + def postprocess(self, results: List[OutputType], input_data: List[InputType]) -> List[OutputType]: + """Create graph nodes and relationships.""" + pass + +# Export types for easy access +InputType = MyEnricher.InputType +OutputType = MyEnricher.OutputType +``` + +The `InputType` and `OutputType` class attributes define what data the enricher accepts and returns. These should be Pydantic types from the `flowsint-types` package defined as base types (e.g., `Domain`, not `List[Domain]`). The base class uses these type definitions to automatically generate JSON schemas for the API and handle validation automatically. + +At the end of the file, you should export the types for easy access by other modules. + +### The two phases + +Understanding the two execution phases is crucial for writing effective enrichers. + +**Scanning** is where the real work happens. This async method receives validated input data as a list of `InputType` instances and executes your intelligence gathering logic. You might instantiate tools, call external APIs, process results, and build up your output data. This phase should focus purely on gathering and processing data without worrying about the graph database. The base class automatically handles input validation through Pydantic before the scan phase begins. + +**Postprocessing** creates the graph database structure. After scanning completes, this method receives both the results and the original input. It creates Neo4j nodes for each entity, establishes relationships between them, and returns the final results. This separation keeps graph logic separate from business logic. + +## Creating a simple enricher + +Let's walk through creating a complete enricher from scratch. We'll build an enricher that converts domains to IP addresses using DNS resolution. + +### Setting up the file structure + +Enrichers are organized by their input type. Create a new file in the appropriate directory under `flowsint-enrichers/src/flowsint_enrichers/`: + +```bash +cd flowsint-enrichers/src/flowsint_enrichers/domain/ +touch to_ip.py +``` + +If you're creating an enricher for a new input type, you may need to create a new directory first. + +### Implementing the basic structure + +Start with the imports and class definition: + +```python +import socket +from typing import List +from flowsint_enrichers.registry import flowsint_enricher +from flowsint_core.core.enricher_base import Enricher +from flowsint_core.core.logger import Logger +from flowsint_types import Domain, Ip + +@flowsint_enricher +class DomainToIpEnricher(Enricher): + """Resolves domain names to their IP addresses using DNS.""" + + # Define types as base types (not lists) + InputType = Domain + OutputType = Ip + + @classmethod + def name(cls) -> str: + return "domain_to_ip" + + @classmethod + def category(cls) -> str: + return "Domain" + + @classmethod + def key(cls) -> str: + return "domain" + + @classmethod + def documentation(cls) -> str: + return """ + This enricher resolves domain names to their IP addresses using + standard DNS queries. It accepts a list of domains and returns + the corresponding IP addresses. + """ + +# Export types at the end of the file +InputType = DomainToIpEnricher.InputType +OutputType = DomainToIpEnricher.OutputType +``` + +The `name()` method returns a unique identifier for this enricher. Use lowercase with underscores, following the pattern `inputtype_to_outputtype`. The `category()` groups related enrichers together in the UI. The `key()` specifies which field serves as the primary identifier, typically matching the input type. + +### Implementing the scan logic + +The scan method contains your core intelligence gathering logic. It receives a list of validated `InputType` instances and returns a list of `OutputType` instances. + +```python + async def scan(self, data: List[InputType]) -> List[OutputType]: + """ + Resolve each domain to its IP address. + + Args: + data: List of Domain objects to resolve + + Returns: + List of Ip objects + """ + results: List[OutputType] = [] + + for domain in data: + try: + # Perform DNS resolution + ip_address = socket.gethostbyname(domain.domain) + # Create IP object + ip = Ip(address=ip_address) + results.append(ip) + # Log successful resolution + Logger.info( + self.sketch_id, + {"message": f"Resolved {domain.domain} to {ip_address}"} + ) + except socket.gaierror as e: + # DNS resolution failed + Logger.info( + self.sketch_id, + {"message": f"Failed to resolve {domain.domain}: {e}"} + ) + continue + except Exception as e: + # Unexpected error + Logger.error( + self.sketch_id, + {"message": f"Error resolving {domain.domain}: {e}"} + ) + continue + return results +``` + +This implementation iterates through each domain, performs DNS resolution, creates an IP object for successful resolutions, and logs both successes and failures. The error handling ensures that failures don't crash the entire enricher, which is important when processing many domains. + +The input data has already been validated by Pydantic before reaching the scan method, so you can trust that all items are proper `Domain` objects. + +### Implementing postprocessing + +The postprocess method creates graph database nodes and relationships using the new simplified API: + +```python + def postprocess(self, results: List[OutputType], input_data: List[InputType] = None) -> List[OutputType]: + """ + Create graph nodes and relationships. + + Args: + results: IP objects from scan phase + input_data: Original Domain objects (preprocessed input) + + Returns: + IP objects (unchanged) + """ + # Create nodes and relationships + for domain, ip in zip(input_data, results): + # Create nodes by passing Pydantic objects directly + self.create_node(domain) + self.create_node(ip) + + # Create relationship by passing Pydantic objects directly + self.create_relationship(domain, ip, "RESOLVES_TO") + + # Log the operation + self.log_graph_message( + f"IP found for domain {domain.domain} -> {ip.address}" + ) + + return results +``` + +You can pass Pydantic objects directly to `create_node()` and `create_relationship()`. The methods automatically infer the node types, primary keys, and property values from the Pydantic models. + +The `create_node()` method accepts a Pydantic object and automatically creates a Neo4j node with the correct label and properties. The `create_relationship()` method takes two Pydantic objects and a relationship type string, inferring all necessary information from the objects. + +## Creating an enricher with tools + +Most enrichers use external tools for data gathering. Let's create an enricher that uses the Subfinder tool for subdomain enumeration. + +### Importing the tool + +Start by importing the tool along with your other dependencies: + +```python +from typing import List +from flowsint_core.core.enricher_base import Enricher +from flowsint_enrichers.registry import flowsint_enricher +from flowsint_core.core.logger import Logger +from flowsint_types import Domain +from tools.network.subfinder import SubfinderTool + +@flowsint_enricher +class SubdomainEnricher(Enricher): + """Enumerates subdomains for given domains using Subfinder.""" + + # Define types as base types + InputType = Domain + OutputType = Domain + + @classmethod + def name(cls) -> str: + return "domain_to_subdomains" + + @classmethod + def category(cls) -> str: + return "Domain" + + @classmethod + def key(cls) -> str: + return "domain" + +# Export types +InputType = SubdomainEnricher.InputType +OutputType = SubdomainEnricher.OutputType +``` + +### Using the tool in scan + +The scan method instantiates and uses the tool: + +```python + async def scan(self, data: List[InputType]) -> List[OutputType]: + """ + Find subdomains using Subfinder tool. + Args: + data: List of Domain objects + Returns: + List of discovered subdomain Domain objects + """ + results: List[OutputType] = [] + # Instantiate the tool + subfinder = SubfinderTool() + + for domain in data: + Logger.info( + self.sketch_id, + {"message": f"Enumerating subdomains for {domain.domain}"} + ) + try: + # Launch the tool + subdomains = subfinder.launch(domain.domain) + # Convert strings to Domain objects + for subdomain in subdomains: + results.append(Domain(domain=subdomain, root=False)) + Logger.info( + self.sketch_id, + {"message": f"Found {len(subdomains)} subdomains for {domain.domain}"} + ) + except Exception as e: + Logger.error( + self.sketch_id, + {"message": f"Error enumerating subdomains for {domain.domain}: {e}"} + ) + continue + return results +``` + +Notice how the tool returns raw strings, and the enricher converts them into proper Domain objects. This separation of concerns keeps tools simple while enrichers handle type conversion. + +### Creating graph nodes and relationships + +The postprocess phase creates parent-child relationships between domains and subdomains: + +```python + def postprocess(self, results: List[OutputType], input_data: List[InputType]) -> List[OutputType]: + """ + Create graph nodes and relationships for domains and subdomains. + + Args: + results: Discovered subdomain Domain objects + input_data: Original parent Domain objects + + Returns: + Subdomain Domain objects + """ + # Create nodes for parent domains + for domain in input_data: + self.create_node(domain) + + # Create nodes for subdomains and relationships + for subdomain in results: + self.create_node(subdomain) + + # Extract parent domain name and create relationship + parent_domain_name = self._extract_parent_domain(subdomain.domain) + parent_domain = Domain(domain=parent_domain_name) + + # Create relationship using Pydantic objects + self.create_relationship(parent_domain, subdomain, "HAS_SUBDOMAIN") + + # Log the operation + self.log_graph_message( + f"Subdomain found: {parent_domain_name} -> {subdomain.domain}" + ) + + return results + + def _extract_parent_domain(self, subdomain: str) -> str: + """Extract parent domain from subdomain.""" + parts = subdomain.split('.') + if len(parts) >= 2: + return '.'.join(parts[-2:]) + return subdomain +``` + +## Adding parameters to enrichers + +Many enrichers need user-configurable parameters. Let's create an enricher that scans ports with configurable options. + +### Defining the parameter schema + +The `get_params_schema()` class method defines what parameters your enricher accepts: + +```python +from typing import List, Dict, Any, Optional +from flowsint_enrichers.registry import flowsint_enricher +from flowsint_core.core.enricher_base import Enricher +from flowsint_types import Ip, Port +from tools.network.naabu import NaabuTool + +@flowsint_enricher +class IpToPortsEnricher(Enricher): + """Scans IP addresses for open ports.""" + + # Define types as base types + InputType = Ip + OutputType = Port + + @classmethod + def name(cls) -> str: + return "ip_to_ports" + + @classmethod + def category(cls) -> str: + return "IP" + + @classmethod + def key(cls) -> str: + return "address" + + @classmethod + def get_params_schema(cls) -> List[Dict[str, Any]]: + """Define configurable parameters for this enricher.""" + return [ + { + "name": "mode", + "type": "select", + "description": "Scan mode: active scanning or passive enumeration", + "required": True, + "default": "passive", + "options": [ + {"label": "Passive", "value": "passive"}, + {"label": "Active", "value": "active"}, + ], + }, + { + "name": "port_range", + "type": "string", + "description": "Port range to scan (e.g., '1-1000' or '80,443,8080')", + "required": False, + }, + { + "name": "top_ports", + "type": "select", + "description": "Scan only the most common ports", + "required": False, + "options": [ + {"label": "Top 100", "value": "100"}, + {"label": "Top 1000", "value": "1000"}, + ], + }, + { + "name": "PDCP_API_KEY", + "type": "vaultSecret", + "description": "ProjectDiscovery Cloud Platform API key for passive mode", + "required": False, + }, + ] + +# Export types +InputType = IpToPortsEnricher.InputType +OutputType = IpToPortsEnricher.OutputType +``` + +The parameter schema defines the type, description, whether it's required, default values, and for select parameters, the available options. The `vaultSecret` type integrates with Flowsint's encrypted credential storage. + +### Using parameters in your enricher + +Parameters are accessed through `self.params` in your scan method: + +```python + async def scan(self, data: List[InputType]) -> List[OutputType]: + """ + Scan IPs for open ports using configured parameters. + Args: + data: List of Ip objects to scan + Returns: + List of Port objects + """ + results: List[OutputType] = [] + # Extract parameters + mode = self.params.get("mode", "passive") + port_range = self.params.get("port_range") + top_ports = self.params.get("top_ports") + api_key = self.get_secret("PDCP_API_KEY") + + # Instantiate tool + naabu = NaabuTool() + + for ip in data: + Logger.info( + self.sketch_id, + {"message": f"Scanning {ip.address} in {mode} mode"} + ) + try: + # Launch tool with parameters + scan_results = naabu.launch( + target=ip.address, + mode=mode, + port_range=port_range, + top_ports=top_ports, + api_key=api_key + ) + # Convert tool results to Port objects + for result in scan_results: + port = Port( + number=result.get("port"), + protocol=result.get("protocol", "tcp").upper(), + state="open", + service=result.get("service"), + banner=result.get("version") + ) + results.append(port) + except Exception as e: + Logger.error( + self.sketch_id, + {"message": f"Error scanning {ip.address}: {e}"} + ) + continue + return results +``` + +## Handling multiple output types + +Some enrichers produce multiple types of results. You can define a custom return type using Pydantic: + +```python +from pydantic import BaseModel +from flowsint_enrichers.registry import flowsint_enricher +from flowsint_core.core.enricher_base import Enricher +from typing import List +from flowsint_types import Website, Email, Phone + +class CrawlerResults(BaseModel): + """Results from web crawler including multiple entity types.""" + website: Website + emails: List[Email] = [] + phones: List[Phone] = [] + +@flowsint_enricher +class WebsiteToCrawlerEnricher(Enricher): + """Crawls websites to extract emails and phone numbers.""" + + # Define types as base types + InputType = Website + OutputType = CrawlerResults + + async def scan(self, data: List[InputType]) -> List[OutputType]: + """Crawl websites and extract contact information.""" + from tools.network.reconcrawl import ReconCrawlTool + + results: List[OutputType] = [] + crawler_tool = ReconCrawlTool() + + for website in data: + try: + # Launch crawler + crawl_data = crawler_tool.launch(website.url) + + # Extract entities + emails = [Email(email=e) for e in crawl_data.get("emails", [])] + phones = [Phone(number=p) for p in crawl_data.get("phones", [])] + + # Create result object + result = CrawlerResults( + website=website, + emails=emails, + phones=phones + ) + results.append(result) + + except Exception as e: + Logger.error(self.sketch_id, {"message": f"Crawl error: {e}"}) + + return results + + def postprocess(self, results: List[OutputType], input_data: List[InputType]) -> List[OutputType]: + """Create nodes for all discovered entities.""" + for result in results: + # Create website node using Pydantic object + self.create_node(result.website) + + # Create email nodes and relationships + for email in result.emails: + self.create_node(email) + self.create_relationship(result.website, email, "HAS_EMAIL") + + # Create phone nodes and relationships + for phone in result.phones: + self.create_node(phone) + self.create_relationship(result.website, phone, "HAS_PHONE") + + self.log_graph_message( + f"Processed {len(result.emails)} emails and {len(result.phones)} phones from {result.website.url}" + ) + + return results + +# Export types +InputType = WebsiteToCrawlerEnricher.InputType +OutputType = WebsiteToCrawlerEnricher.OutputType +``` + +## Registering your enricher + +You don't need to register your enricher anywhere, adding the decorator `@flowsint_enricher` to your enricher class triggers the auto discovery. + +```python +from flowsint_enrichers.registry import flowsint_enricher +from flowsint_core.core.enricher_base import Enricher + +@flowsint_enricher +class MyEnricher(Enricher): +... +``` + +## Testing your enricher + +Creating tests helps ensure your enricher works correctly and makes debugging easier. Create a test file in `flowsint-enrichers/tests/`: + +```python +# tests/test_domain_to_ip.py +import pytest +from flowsint_enrichers.domain.to_ip import DomainToIpEnricher +from flowsint_types import Domain, Ip + +@pytest.mark.asyncio +async def test_enricher_metadata(): + """Test enricher metadata is correctly defined.""" + assert DomainToIpEnricher.name() == "domain_to_ip" + assert DomainToIpEnricher.category() == "Domain" + assert DomainToIpEnricher.key() == "domain" + +@pytest.mark.asyncio +async def test_type_definitions(): + """Test InputType and OutputType are correctly defined.""" + assert DomainToIpEnricher.InputType == Domain + assert DomainToIpEnricher.OutputType == Ip + +@pytest.mark.asyncio +async def test_scan(): + """Test DNS resolution works.""" + enricher = DomainToIpEnricher(sketch_id="test", scan_id="test") + input_data = [Domain(domain="example.com")] + results = await enricher.scan(input_data) + + assert len(results) > 0 + assert isinstance(results[0], Ip) + assert results[0].address # Should have an IP address +``` + +These tests verify that your enricher's metadata is correct, type definitions are properly set, and the scan logic produces expected results. Input validation is handled automatically by Pydantic, so you don't need to test preprocessing separately. + +## Best practices + +When creating enrichers, think carefully about error handling. Intelligence gathering involves many external systems that can fail in unpredictable ways. Your enricher should handle errors gracefully, log failures clearly, and continue processing remaining items rather than crashing entirely. + +Always use the Logger utility for tracking progress and errors. The logger integrates with Flowsint's monitoring system and helps users understand what's happening during long-running enrichers. Log successful operations at the info level and errors at the error level. + +Define InputType and OutputType as base types (e.g., `Domain`, not `List[Domain]`). The base class automatically handles the list wrapping and validation. This makes the type definitions cleaner and more intuitive. + +Always export your types at the end of the file using: +```python +InputType = YourEnricher.InputType +OutputType = YourEnricher.OutputType +``` + +Use the simplified graph API by passing Pydantic objects directly to `create_node()` and `create_relationship()`. This eliminates boilerplate code and reduces errors. The methods automatically infer node types, primary keys, and properties from your Pydantic models. + +Separate concerns between the two phases. Scanning should focus on gathering and processing data. Postprocessing should create graph structures. Input validation happens automatically through Pydantic, so you don't need to handle it manually. + +Use type hints everywhere. They provide automatic validation, better IDE support, and serve as inline documentation. The InputType and OutputType class attributes should always be Pydantic types from the flowsint-types package. + +When working with tools, remember that they return raw data structures. Your enricher is responsible for converting tool output into proper Flowsint types. This type conversion is typically done in the scan phase. + +Document your enricher thoroughly. The class docstring, documentation method, and parameter descriptions all appear in the UI. Clear documentation helps users understand what your enricher does and how to configure it. + +### Handling API Rate Limits + +When working with rate-limited APIs, add delays between requests: + +```python + async def scan(self, data: InputType) -> OutputType: + """Scan with rate limiting to respect API limits.""" + import asyncio + results = [] + delay_seconds = 1 # Delay between requests + for item in data: + result = await self._query_api(item) + if result: + results.append(result) + # Respect rate limits + await asyncio.sleep(delay_seconds) + return results +``` + +### Fallback data sources + +Implement fallback logic when primary sources fail: + +```python + async def scan(self, data: InputType) -> OutputType: + """Try multiple data sources with fallback logic.""" + results = [] + + for domain in data: + # Try primary source + result = self._query_primary_source(domain) + + if not result: + # Fall back to secondary source + Logger.info( + self.sketch_id, + {"message": f"Primary source failed for {domain}, trying fallback"} + ) + result = self._query_fallback_source(domain) + + if result: + results.append(result) + + return results +``` + +## Troubleshooting + +If your enricher doesn't appear in the API, verify that you've applied the `@flowsint_enricher` decorator to your class, that the file lives under `flowsint-enrichers/src/flowsint_enrichers/`, and that you've restarted the API server. Auto-discovery via `load_all_enrichers()` runs at startup, so file additions require a restart. + +For import errors, make sure all your dependencies are installed and the enricher file has no syntax errors. Check that you're importing from the correct packages. + +If the scan method isn't finding any results, add logging statements to debug what's happening. Verify that tools are installed and accessible, API keys are valid if required, and input data is in the expected format. + +When graph relationships aren't appearing, check that you're creating both nodes and relationships in the postprocess method. Verify that the relationship type name is correct and that you're passing the right node objects to `create_relationship()`. + +## Next steps + +Once you've created and registered your enricher, it becomes available through the API for users to run. Enrichers can be chained together into Flows where the output of one enricher feeds into the input of another. This enables complex intelligence gathering sequences. + +Remember that enrichers are the heart of Flowsint's intelligence gathering capabilities. Well-designed enrichers that handle errors gracefully, log progress clearly, and create meaningful graph relationships make the entire platform more powerful and user-friendly. + +If you create new enrichers that you think can help the community, it's highly appreciated that you open-source them. Help the community as much as it helps you ! diff --git a/docs/developers/managing-tools.mdx b/docs/developers/managing-tools.mdx new file mode 100644 index 0000000..7571003 --- /dev/null +++ b/docs/developers/managing-tools.mdx @@ -0,0 +1,512 @@ +--- +title: "Managing tools" +description: "This guide explains how to create a new tool in the Flowsint ecosystem. Tools are low-level wrappers around external utilities, Docker containers, and APIs that enrichers use to gather intelligence. Understanding the tool architecture will help you extend Flowsint's capabilities with new data sources and reconnaissance utilities." +category: "Developers" +order: 9 +author: "Flowsint Team" +tags: ["tutorial", "developers", "creating-a-new-tool"] +version: "1.2.8" +last_updated_at: "2026-05-15" +--- + +## Understanding tools + +Tools in Flowsint serve as abstraction layers between enrichers and external systems. They provide a consistent interface for executing Docker containers, calling APIs, or running python libraries. While enrichers handle high-level orchestration and graph database operations, tools focus exclusively on executing external commands and returning raw results. + +Every tool implements a basic interface with methods for naming, categorization, and execution. Tools don't know anything about Pydantic types, Neo4j graphs, or the broader Flowsint architecture. They just wrap external functionality and return data. + +Flowsint currently includes tools for subdomain enumeration, port scanning, DNS queries, WHOIS lookups, web crawling, and business intelligence. + +## Tool architecture + +The tool system has a two-tier inheritance structure. At the base level, you have the abstract `Tool` class that defines the interface every tool must implement. For tools that run in Docker containers, there's an intermediate `DockerTool` class that handles all the container lifecycle management. + +### The Tool base class + +Every tool inherits from the abstract `Tool` class, which lives at `flowsint-enrichers/src/tools/base.py`. Here's what it looks like: + +```python +from abc import ABC, abstractmethod +from typing import Any + +class Tool(ABC): + """Abstract base class for all tools.""" + + @classmethod + @abstractmethod + def name(cls) -> str: + """Return the tool name.""" + pass + + @classmethod + @abstractmethod + def category(cls) -> str: + """Return the tool category.""" + pass + + @classmethod + @abstractmethod + def description(cls) -> str: + """Return a description of what the tool does.""" + pass + + @classmethod + @abstractmethod + def version(cls) -> str: + """Return the tool version.""" + pass + + @abstractmethod + def launch(self, value: str, *args, **kwargs) -> Any: + """Execute the tool and return results.""" + pass +``` + +Any tool you create must implement these five methods. The first four are class methods that provide metadata about the tool. The `launch` method is where the actual work happens. + +### The DockerTool class + +Most security and reconnaissance tools run in Docker containers for isolation and portability. The `DockerTool` class at `flowsint-enrichers/src/tools/dockertool.py` provides all the infrastructure for running containerized tools. + +When you inherit from `DockerTool`, you get automatic image management, container execution, volume mounting, environment variable handling, and cleanup. You just specify the Docker image name and implement how to construct the command. + +Here's a simplified view of what `DockerTool` provides: + +```python +class DockerTool(Tool): + """Base class for tools that run in Docker containers.""" + + def __init__(self, image: str, default_tag: str = "latest"): + """Initialize with Docker image information.""" + self.image = image + self.default_tag = default_tag + self.docker_client = docker.from_env() + + def install(self) -> None: + """Pull the Docker image if not already present.""" + # Pulls image from Docker Hub + pass + + def is_installed(self) -> bool: + """Check if the Docker image exists locally.""" + # Checks local images + pass + + def launch(self, command: str, volumes: dict = None, + timeout: int = 30, environment: dict = None) -> Any: + """Run a command in the Docker container.""" + # Executes container and returns output + pass +``` + +The `launch` method in `DockerTool` handles container execution. It sets up the environment, mounts volumes if needed, runs the container, captures output, and cleans up afterward. + +## Creating a simple API-based tool + +Let's start with the simpler case of creating a tool that calls an external API. We'll create a hypothetical tool for querying a threat intelligence service. + +### File structure + +Create a new python file in the appropriate category directory under `flowsint-enrichers/src/tools/`. For a security-related tool, you might use `tools/security/`: + +```bash +cd flowsint-enrichers/src/tools/security/ +touch threat_intel.py +``` + +If the category directory doesn't exist, create it first and add an `__init__.py` file to make it a python package. + +### Basic implementation + +Here's a complete example of an API-based tool: + +```python +from tools.base import Tool +from typing import Any, Dict, List, Optional +import requests + +class ThreatIntelTool(Tool): + """Query threat intelligence data from an external API.""" + + api_endpoint = "https://api.threatintel.example.com/v1" + + @classmethod + def name(cls) -> str: + """Return the tool name.""" + return "threatintel" + + @classmethod + def category(cls) -> str: + """Return the category this tool belongs to.""" + return "Threat Intelligence" + + @classmethod + def description(cls) -> str: + """Return a description of what this tool does.""" + return "Queries threat intelligence data for IPs, domains, and hashes" + + @classmethod + def version(cls) -> str: + """Return the tool version.""" + return "1.0.0" + + def launch( + self, + indicator: str, + indicator_type: str = "ip", + api_key: Optional[str] = None + ) -> List[Dict[str, Any]]: + """ + Query the threat intelligence API. + + Args: + indicator: The indicator to query (IP, domain, hash, etc.) + indicator_type: Type of indicator (ip, domain, hash) + api_key: API key for authentication + + Returns: + List of threat intelligence records + """ + if not api_key: + raise ValueError("API key is required") + + headers = { + "Authorization": f"Bearer {api_key}", + "Content-Type": "application/json" + } + + params = { + "indicator": indicator, + "type": indicator_type + } + + try: + response = requests.get( + f"{self.api_endpoint}/query", + headers=headers, + params=params, + timeout=30 + ) + response.raise_for_status() + return response.json().get("results", []) + + except requests.exceptions.RequestException as e: + print(f"Error querying threat intel API: {e}") + return [] +``` + +This tool follows a straightforward pattern. The class methods provide metadata that enrichers and the registry use. The `launch` method implements the actual API interaction, handling authentication, making the request, and returning structured data. + +Notice how the tool returns simple python data structures like lists and dictionaries. Tools don't know about Pydantic types or Flowsint models. That's the enricher's job. + +## Creating a docker-based tool + +Docker-based tools are more common in Flowsint because most reconnaissance utilities need specific dependencies and isolated environments. Let's walk through creating a tool that wraps a hypothetical Docker-based subdomain scanner. + +### Setting up the class + +Start by inheriting from `DockerTool` and providing the Docker image information: + +```python +from tools.dockertool import DockerTool +from typing import List, Optional, Any + +class MySubdomainTool(DockerTool): + """Wrapper for a Docker-based subdomain enumeration tool.""" + + image = "org/subdomain-scanner" + default_tag = "latest" + + def __init__(self): + """Initialize the tool with Docker image information.""" + super().__init__(self.image, self.default_tag) +``` + +The `image` and `default_tag` class attributes tell `DockerTool` which Docker image to use. When you instantiate the tool, it will automatically connect to the Docker daemon. + +### Implementing the launch method + +The `launch` method needs to construct the command that runs inside the container and handle the results: + +```python + def launch( + self, + domain: str, + timeout: int = 300, + wordlist: Optional[str] = None + ) -> List[str]: + """ + Enumerate subdomains for a given domain. + + Args: + domain: Target domain to enumerate + timeout: Maximum execution time in seconds + wordlist: Optional path to custom wordlist file + + Returns: + List of discovered subdomain strings + """ + # Ensure the Docker image is available + if not self.is_installed(): + self.install() + + # Build the command that runs inside the container + command = f"-d {domain}" + + if wordlist: + command += f" -w {wordlist}" + + # Add JSON output flag for easier parsing + command += " -json" + + # Execute the container + try: + result = super().launch( + command=command, + timeout=timeout + ) + + # Parse the output + subdomains = self._parse_output(result) + return subdomains + + except Exception as e: + print(f"Error running subdomain scanner: {e}") + return [] + + def _parse_output(self, output: str) -> List[str]: + """Parse the tool output and extract subdomains.""" + import json + + subdomains = [] + for line in output.strip().split('\n'): + if not line: + continue + try: + data = json.loads(line) + if 'subdomain' in data: + subdomains.append(data['subdomain']) + except json.JSONDecodeError: + continue + + return list(set(subdomains)) # Remove duplicates +``` + +This implementation shows several important patterns. First, it checks if the Docker image is installed and pulls it if necessary. Second, it constructs the command string that will run inside the container. Third, it calls the parent class's `launch` method to handle the actual container execution. Finally, it parses the output into a clean python data structure. + +### Handling volumes + +Some tools need access to files on the host system. You can mount volumes when calling the parent's `launch` method: + +```python + def launch(self, domain: str, wordlist_path: str = None) -> List[str]: + """Run the tool with optional wordlist file.""" + + command = f"-d {domain}" + volumes = None + + if wordlist_path: + # Mount the wordlist file into the container + volumes = { + wordlist_path: { + 'bind': '/wordlist.txt', + 'mode': 'ro' # read-only + } + } + command += " -w /wordlist.txt" + + result = super().launch( + command=command, + volumes=volumes + ) + + return self._parse_output(result) +``` + +The volumes dictionary maps host paths to container paths. You can specify the mount mode as 'ro' for read-only or 'rw' for read-write. + +### Using environment variables + +For tools that need API keys or configuration through environment variables: + +```python + def launch(self, domain: str, api_key: Optional[str] = None) -> List[str]: + """Run the tool with optional API key for enhanced scanning.""" + + command = f"-d {domain}" + environment = {} + + if api_key: + environment['API_KEY'] = api_key + + result = super().launch( + command=command, + environment=environment + ) + + return self._parse_output(result) +``` + +## Testing your tool + +Creating tests for your tool helps ensure it works correctly and makes it easier to catch regressions. Create a test file in `flowsint-enrichers/tests/tools/` that mirrors your tool's location: + +```python +# tests/tools/security/test_threat_intel.py +from tools.security.threat_intel import ThreatIntelTool +import pytest + +def test_tool_metadata(): + """Test that tool metadata is correctly defined.""" + assert ThreatIntelTool.name() == "threatintel" + assert ThreatIntelTool.category() == "Threat Intelligence" + assert "threat" in ThreatIntelTool.description().lower() + +def test_tool_launch_requires_api_key(): + """Test that launch method requires an API key.""" + tool = ThreatIntelTool() + with pytest.raises(ValueError): + tool.launch("192.0.2.1") + +def test_tool_launch_with_api_key(monkeypatch): + """Test successful API query with mocked response.""" + tool = ThreatIntelTool() + + # Mock the requests.get call + def mock_get(*args, **kwargs): + class MockResponse: + def raise_for_status(self): + pass + def json(self): + return {"results": [{"indicator": "192.0.2.1", "threat_level": "high"}]} + return MockResponse() + + monkeypatch.setattr("requests.get", mock_get) + + results = tool.launch("192.0.2.1", api_key="test_key") + assert len(results) == 1 + assert results[0]["indicator"] == "192.0.2.1" +``` + +For docker-based tools, your tests need Docker to be running: + +```python +# tests/tools/network/test_my_subdomain_tool.py +from tools.network.my_subdomain_tool import MySubdomainTool +import pytest + +@pytest.mark.docker +def test_tool_install(): + """Test that the Docker image can be pulled.""" + tool = MySubdomainTool() + tool.install() + assert tool.is_installed() + +@pytest.mark.docker +def test_tool_launch(): + """Test running the tool against a domain.""" + tool = MySubdomainTool() + results = tool.launch("example.com") + assert isinstance(results, list) +``` + +The `@pytest.mark.docker` decorator helps you separate tests that require Docker from those that don't. + +## Best practices + +When creating tools, focus on simplicity and single responsibility. Each tool should wrap exactly one external utility or API. Don't try to combine multiple data sources in a single tool. That's what enrichers are for. + +Always handle errors gracefully. Network requests fail, Docker containers crash, and APIs return unexpected data. Your tool should catch these errors, log them appropriately, and return empty results or raise clear exceptions rather than crashing. + +Return simple data structures from the `launch` method. Use lists, dictionaries, strings, and numbers. Don't return Pydantic models or other complex objects. Remember that tools are low-level utilities that enrichers build upon. + +For Docker tools, always check if the image is installed before running it. The pattern of checking `is_installed()` and calling `install()` if necessary ensures the tool works even on fresh installations. + +When parsing tool output, be defensive. External tools can return unexpected formats, partial results, or garbage data. Validate and clean the output before returning it. Use try-except blocks around parsing logic. + +Document your tool thoroughly. The docstrings and parameter descriptions help other developers understand how to use your tool. Future enrichers will rely on this documentation. + +## Integrating your tool + +Unlike types, tools don't need to be explicitly registered in a central registry. Enrichers import and use them directly. When you create an enricher that uses your new tool, you simply import it: + +```python +# In an enricher file +from tools.security.threat_intel import ThreatIntelTool + +class IpToThreatIntelEnricher(Enricher): + async def scan(self, data: List[Ip]) -> List[ThreatReport]: + tool = ThreatIntelTool() + results = [] + + for ip in data: + intel = tool.launch( + indicator=ip.address, + indicator_type="ip", + api_key=api_key + ) + # Process results... + + return results +``` + +The enricher instantiates your tool, calls its `launch` method with appropriate parameters, and processes the results into Flowsint types. + +## Common patterns + +Several patterns appear frequently in Flowsint tools. Understanding these will help you write tools that fit naturally into the ecosystem. + +### The install-check pattern + +Most Docker tools follow this pattern at the start of `launch`: + +```python +def launch(self, ...): + if not self.is_installed(): + self.install() + + # Continue with execution +``` + +This ensures the docker image is available before trying to run it. + +### The command builder pattern + +Complex tools often build commands incrementally based on parameters: + +```python +def launch(self, target: str, mode: str = "fast", verbose: bool = False): + command = f"-target {target}" + + if mode == "thorough": + command += " --thorough" + + if verbose: + command += " -v" + + result = super().launch(command) +``` + +### The output parser pattern + +Many tools separate execution from parsing: + +```python +def launch(self, ...): + raw_output = super().launch(command) + return self._parse_output(raw_output) + +def _parse_output(self, output: str) -> List[Dict]: + """Parse raw tool output into structured data.""" + # Parsing logic here +``` + +This separation makes the code easier to test and maintain. + +## Next steps + +Once you've created your tool and tested it, you can build enrichers that use it. Enrichers orchestrate one or more tools to gather intelligence, validate the results, convert them to Flowsint types, and create graph database nodes and relationships. + +If your tool requires API keys or other secrets, enrichers can access them through the vault system. When you implement an enricher that uses your tool, you can define parameters of type `vaultSecret` that pull credentials from the user's encrypted vault. + +Remember that tools are just one layer in the Flowsint architecture. They provide the raw capabilities, but enrichers provide the intelligence and graph-building logic that makes the platform powerful. diff --git a/docs/developers/managing-types.mdx b/docs/developers/managing-types.mdx new file mode 100644 index 0000000..8235959 --- /dev/null +++ b/docs/developers/managing-types.mdx @@ -0,0 +1,1253 @@ +--- +title: "Managing types" +description: "This guide walks you through the process of creating a new data type in the Flowsint ecosystem and integrating it throughout the platform. Types in Flowsint serve as the foundation for all data modeling, providing structure, validation, and schema generation for the entire system." +category: "Developers" +order: 8 +author: "Flowsint Team" +tags: ["tutorial", "developers", "creating-a-new-type"] +version: "1.2.8" +last_updated_at: "2026-05-15" +--- + +## Understanding the type system + +The Flowsint type system is built on Pydantic models and lives in the `flowsint-types` package. Every type is a python class that inherits from `FlowsintType`, which itself inherits from `pydantic.BaseModel`, **and must be decorated with `@flowsint_type`** to be registered in the global type registry. This provides automatic validation, serialization, JSON schema generation, auto-discovery, and graph-specific functionality like automatic label generation. The architecture is deliberately simple with minimal inheritance hierarchies. Each type inherits from FlowsintType and defines its own fields and behavior. + +The package structure is straightforward. Inside `flowsint-types/src/flowsint_types/`, you'll find individual python files for each type. Most types get their own file, though closely related types sometimes share a file. For example, `wallet.py` contains `CryptoWallet`, `CryptoWalletTransaction`, and `CryptoNFT` because they work together as a conceptual unit. + +Currently, Flowsint includes 39 built-in types covering everything from network entities like domains and IPs to identity information like individuals and organizations, security data like credentials and breaches, and financial information like bank accounts and crypto wallets. + +### What is FlowsintType? + +`FlowsintType` is the base class for all Flowsint entity types. It extends Pydantic's `BaseModel` with additional functionality specific to Flowsint's graph database and UI needs: + +```python +class FlowsintType(BaseModel): + """Base class for all Flowsint entity types with nodeLabel support. + nodeLabel is optional but computed at definition time. + + All classes that inherit from FlowsintType must be decorated with @flowsint_type + to be registered in the global TYPE_REGISTRY and accessed by their class name. + + Usage: + from flowsint_types.registry import flowsint_type + + @flowsint_type + class Domain(FlowsintType): + domain: str + """ + + nodeLabel: Optional[str] = Field( + None, + description="UI-readable label for this entity, the one used on the graph.", + title="Label", + ) + + # Allow extra keys to support additional properties from user + class ConfigDict: + extra = "allow" +``` + +The `nodeLabel` field is automatically set by types using a `@model_validator` decorator, and this label is what appears on graph nodes in the Neo4j database and in the frontend UI. Every type should compute its own meaningful label based on its fields. + +The `ConfigDict` with `extra = "allow"` means types accept additional properties beyond their defined fields, which is useful for user-provided metadata. + +### The `@flowsint_type` decorator + +Every type **must** be decorated with `@flowsint_type` from `flowsint_types.registry`. This decorator registers the type in the global `TYPE_REGISTRY`, which enables: + +- Auto-discovery of all types at startup via `load_all_types()` +- Lookup by class name (e.g., `TYPE_REGISTRY.get("Domain")`) +- Lookup by lowercase name (e.g., `TYPE_REGISTRY.get_lowercase("domain")`) for Neo4j matching + +```python +from flowsint_types.registry import flowsint_type +from .flowsint_base import FlowsintType + +@flowsint_type # Required for registration +class MyType(FlowsintType): + ... +``` + +Without this decorator, your type will not be discoverable by the system. + +## Creating a new type + +Let's walk through the process of creating a new type from scratch. We'll use a hypothetical `Vehicle` type as our example. + +### Setting up the file + +Start by creating a new python file in the types directory. The filename should be lowercase and match your type name in snake_case. For a `Vehicle` type, you would create `vehicle.py`: + +```bash +cd flowsint-types/src/flowsint_types/ +touch vehicle.py +``` + +### Basic structure + +Every type follows the same structural pattern. Here's what a basic type looks like: + +```python +from pydantic import Field, model_validator +from typing import Optional, Self +from .flowsint_base import FlowsintType +from .registry import flowsint_type + +@flowsint_type +class Vehicle(FlowsintType): + """Represents a vehicle with identifying information.""" + + license_plate: str = Field( + ..., + description="Vehicle license plate number", + title="License Plate", + json_schema_extra={"primary": True}, + ) + brand: Optional[str] = Field( + None, + description="Vehicle manufacturer such as Toyota or Ford", + title="Make" + ) + model: Optional[str] = Field( + None, + description="Vehicle model name", + title="Model" + ) + year: Optional[int] = Field( + None, + description="Year of manufacture", + title="Year" + ) + + @model_validator(mode='after') + def compute_label(self) -> Self: + """Compute a human-readable label for this vehicle.""" + if self.brand and self.model and self.year: + self.nodeLabel = f"{self.license_plate} ({self.brand} {self.model} {self.year})" + else: + self.nodeLabel = self.license_plate + return self +``` + +Let's break down the key components: + +**Inheritance, imports, and decorator:** +- The class inherits from `FlowsintType` +- Import `FlowsintType` from `.flowsint_base` +- Import `flowsint_type` from `.registry` and apply it as a decorator +- Import `model_validator` and `Self` from Pydantic for the label computation + +**Docstring:** +- Every type starts with a clear docstring explaining what it represents + +**Field definitions:** +- Each field is defined as a class attribute with type hints +- Use Pydantic's `Field()` function to provide metadata +- Required fields use the ellipsis (`...`) as their default value +- Optional fields use `Optional[Type]` in their type hint and `None` as the default value +- Always provide `description` (for API docs) and `title` (for UI labels) + +**Primary field:** +- The `json_schema_extra={"primary": True}` marks the unique identifier for this type +- This field is used as the key when creating Neo4j nodes +- **Critical:** Every type must have exactly one primary field +- Choose a field that uniquely identifies instances of this type + +**Label computation:** +- The `@model_validator(mode='after')` decorator runs after all field validation +- The method must be named `compute_label` and return `self` +- It sets `self.nodeLabel` to a human-readable string that will appear in the UI and graph +- Handle cases where optional fields might be `None` to avoid ugly labels +- The label should help users quickly identify what this entity is + +### Naming conventions + +Flowsint follows strict naming conventions to maintain consistency across the codebase. Class names use PascalCase (like `Vehicle`, `SocialAccount`, or `CryptoWallet`). Field names use snake_case (like `license_plate`, `phone_number`, or `email_address`). This matches python's standard conventions and makes the codebase more readable. + +### Understanding primary fields and labels + +Two concepts are crucial for every Flowsint type: the **primary field** and the **nodeLabel**. Understanding these will help you create types that work seamlessly with the graph database and UI. + +**Why it matters:** +- When creating Neo4j nodes, this field is used as the key in `MERGE` operations +- It ensures each entity is uniquely identified in the graph +- The graph service extracts this field to determine node uniqueness + +**Rules for primary fields:** +- Every type must have exactly one primary field +- The primary field should uniquely identify instances +- It's typically a required field (using `...` as default) +- Common choices: IDs, usernames, emails, license plates, domain names + +**Examples of good primary fields:** +- `Domain`: `domain` field (e.g., "example.com") +- `Email`: `email` field (e.g., "user@example.com") +- `Username`: `value` field (e.g., "john_doe") +- `Ip`: `address` field (e.g., "192.168.1.1") +- `SocialAccount`: `id` field (computed as "username@platform") + +#### The nodeLabel field and compute_label + +The `nodeLabel` is what users see in the UI and on graph nodes. It should be human-readable and help users quickly understand what an entity represents. + +**How it works:** +1. `FlowsintType` provides a `nodeLabel` field (`Optional[str]`) +2. Your type defines a `compute_label` method to set this field +3. The method runs automatically after validation using `@model_validator(mode='after')` + +**Basic pattern:** + +```python +from pydantic import model_validator +from typing import Self + +@model_validator(mode='after') +def compute_label(self) -> Self: + """Compute a human-readable label.""" + self.nodeLabel = f"@{self.value}" + return self +``` + +**Advanced patterns:** + +When you have optional fields, handle `None` values gracefully: + +```python +@model_validator(mode='after') +def compute_label(self) -> Self: + """Compute label with optional display name.""" + if self.display_name: + self.nodeLabel = f"{self.display_name} (@{self.username.value})" + else: + self.nodeLabel = f"@{self.username.value}" + return self +``` + +For types with multiple identifiers, you might compute a composite ID: + +```python +@model_validator(mode='after') +def compute_label_and_id(self) -> Self: + """Compute both ID and label.""" + # Compute unique ID from username and platform + if self.username and self.platform: + self.id = f"{self.username.value}@{self.platform}" + elif self.username: + self.id = self.username.value + + # Compute display label + if self.display_name: + self.nodeLabel = f"{self.display_name} (@{self.username.value})" + else: + self.nodeLabel = f"@{self.username.value}" + return self +``` + +**Best practices for labels:** +- Keep labels concise but informative +- Include the most identifying information first +- Handle `None` values for optional fields +- Use parentheses or separators to structure complex labels +- Think about what users need to see at a glance on the graph + +**Real-world examples** + +```python +# Simple: just the value +# Username: "@john_doe" +self.nodeLabel = f"@{self.value}" + +# With context: show platform if available +# Username: "@john_doe (twitter)" +if self.platform: + self.nodeLabel = f"@{self.value} ({self.platform})" +else: + self.nodeLabel = f"@{self.value}" + +# Rich: combine multiple fields +# Individual: "John Doe (john@example.com)" +if self.email: + self.nodeLabel = f"{self.full_name} ({self.email})" +else: + self.nodeLabel = self.full_name + +# Complex: show key information +# Breach: "LinkedIn (2021) - 700M records" +self.nodeLabel = f"{self.title} ({self.breachdate.split('-')[0]}) - {self.pwncount:,} records" +``` + +### Working with different field types + +Pydantic supports a wide range of field types beyond simple strings and integers. Here are the most common ones you'll use: + +```python +from pydantic import Field, HttpUrl, model_validator +from typing import Optional, List, Dict, Any, Self +from datetime import datetime +from .flowsint_base import FlowsintType +from .registry import flowsint_type + +@flowsint_type +class ExampleType(FlowsintType): + """Demonstrates various field types.""" + + # Primary identifier + id: str = Field( + ..., + description="Unique identifier", + title="ID", + json_schema_extra={"primary": True} + ) + + # Primitive types + text_field: str = Field(..., description="A text string", title="Text") + number_field: int = Field(..., description="An integer number", title="Number") + decimal_field: float = Field(..., description="A decimal number", title="Decimal") + boolean_field: bool = Field(..., description="True or false value", title="Boolean") + + # Optional fields + optional_text: Optional[str] = Field(None, description="Optional text", title="Optional Text") + + # Collections - note the use of default_factory + tags: List[str] = Field( + default_factory=list, + description="List of tag strings", + title="Tags" + ) + + metadata: Dict[str, Any] = Field( + default_factory=dict, + description="Arbitrary metadata dictionary", + title="Metadata" + ) + + # Special Pydantic types + website: HttpUrl = Field(..., description="A validated URL", title="Website") + timestamp: datetime = Field(..., description="Date and time", title="Timestamp") + + @model_validator(mode='after') + def compute_label(self) -> Self: + """Compute label for this example.""" + self.nodeLabel = f"{self.id} - {self.text_field}" + return self +``` + +When working with mutable types like lists and dictionaries, always use `default_factory` instead of providing a default value directly. Using `default_factory=list` is correct, while using `default=[]` would cause all instances to share the same list object, leading to subtle bugs. + +### Adding validation + +Sometimes you need more sophisticated validation than just type checking. Pydantic lets you add custom validators using the `field_validator` decorator: + +```python +from pydantic import Field, field_validator +from typing import Optional, Any, Self +import ipaddress +from .flowsint_base import FlowsintType +from .registry import flowsint_type + +@flowsint_type +class Ip(FlowsintType): + """Represents an IP address with geolocation and ISP information.""" + + address: str = Field( + ..., + description="IP address", + title="IP Address", + json_schema_extra={"primary": True}, + ) + ... + @field_validator("address") + @classmethod + def validate_ip_address(cls, v: str) -> str: + """Validate that the address is a valid IP address.""" + try: + ipaddress.ip_address(v) + return v + except ValueError: + raise ValueError(f"Invalid IP address: {v}") +``` + +Validators receive the field value and can either return a (potentially modified) value or raise a `ValueError` with an error message. Note that `@field_validator` runs before `@model_validator`, so the field is validated and normalized before the label is computed. + +### Referencing other types + +Types often need to reference other Flowsint types. You can import and use them just like any other python type: + +```python +from pydantic import Field, model_validator +from typing import Optional, Self +from .flowsint_base import FlowsintType +from .registry import flowsint_type +from .email import Email +from .phone import Phone + +@flowsint_type +class Contact(FlowsintType): + """Represents contact information for a person.""" + + name: str = Field( + ..., + description="Contact name", + title="Name", + json_schema_extra={"primary": True} + ) + email: Optional[Email] = Field(None, description="Email address", title="Email") + phone: Optional[Phone] = Field(None, description="Phone number", title="Phone") + + @model_validator(mode='after') + def compute_label(self) -> Self: + """Compute label for this contact.""" + self.nodeLabel = self.name + return self +``` + +For types with circular references or complex relationships, you may need to call `model_rebuild()` at the end of your file: + +```python +from pydantic import Field, model_validator +from typing import Optional, Self +from .flowsint_base import FlowsintType +from .registry import flowsint_type + +@flowsint_type +class CryptoWallet(FlowsintType): + """Represents a cryptocurrency wallet.""" + + address: str = Field( + ..., + description="Wallet address", + title="Address", + json_schema_extra={"primary": True} + ) + + @model_validator(mode='after') + def compute_label(self) -> Self: + """Compute label for this wallet.""" + self.nodeLabel = self.address + return self + +@flowsint_type +class CryptoWalletTransaction(FlowsintType): + """Represents a transaction between wallets.""" + + transaction_id: str = Field( + ..., + description="Unique transaction ID", + title="Transaction ID", + json_schema_extra={"primary": True} + ) + source: CryptoWallet = Field(..., description="Source wallet", title="Source") + target: Optional[CryptoWallet] = Field(None, description="Target wallet", title="Target") + amount: float = Field(..., description="Transaction amount", title="Amount") + + @model_validator(mode='after') + def compute_label(self) -> Self: + """Compute label for this transaction.""" + self.nodeLabel = f"{self.amount} ({self.transaction_id[:8]}...)" + return self + +# Rebuild models to resolve forward references +CryptoWallet.model_rebuild() +CryptoWalletTransaction.model_rebuild() +``` + +## Exporting your type + +Once you've created your type, the `@flowsint_type` decorator handles registration automatically. However, you also need to export it from the package for convenient imports. + +### Updating the package exports + +Open `flowsint-types/src/flowsint_types/__init__.py` and add two things. First, import your new type at the top of the file with the other imports: + +```python +from .address import Location +from .affiliation import Affiliation +from .alias import Alias +# ... other imports ... +from .vehicle import Vehicle # Add your import here +``` + +Second, add your type name to the `__all__` list: + +```python +__all__ = [ + "Location", + "Affiliation", + "Alias", + # ... other types ... + "Vehicle", # Add your type here +] +``` + +The `__all__` list explicitly defines what gets exported when someone does `from flowsint_types import *`. While wildcard imports aren't always recommended, this ensures your type is properly exposed by the package. + +Note that the `@flowsint_type` decorator already registers your type in the `TYPE_REGISTRY` automatically when the module is imported, so the explicit import in `__init__.py` ensures it gets loaded at startup alongside all other types. + +### Installing the package + +After making these changes, you need to reinstall the package for them to take effect: + +```bash +make prod +#or +cd flowsint-types +poetry install +``` + +This updates the package in your development environment so enrichers and the API can import your new type. + +## Integrating with the API + +The final step is making your type available through the API so frontends can discover it and create instances. + +### Categorizing your type + +The API organizes types into logical categories that appear in the frontend. In the `TypeRegistryService._get_category_definitions()` method (located in `flowsint-core/src/flowsint_core/core/services/type_registry_service.py`), you'll find a list of category dictionaries. You need to add your type to an appropriate category or create a new one. + +Each category's `children` list contains tuples of `(TypeName, label_key, icon)`: +- **TypeName**: The PascalCase class name of your type (e.g., `"Vehicle"`) +- **label_key**: The field name used as the display key (e.g., `"license_plate"`) +- **icon**: Optional icon override, or `None` to use the lowercase type name as icon + +You can either add to an existing category or create a new one. + +```python +def _get_category_definitions(self) -> List[Dict[str, Any]]: + """Get the category definitions for types.""" + return [ + { + "id": uuid4(), + "type": "global", + "key": "global_category", + "icon": "phrase", + "label": "Global", + "fields": [], + "children": [ + ("Phrase", "text", None), + ("Location", "address", None), + ], + }, + { + "id": uuid4(), + "type": "person", + "key": "person_category", + "icon": "individual", + "label": "Identities & Entities", + "fields": [], + "children": [ + ("Individual", "full_name", None), + ("Username", "value", "username"), + ("Organization", "name", None), + ], + }, + ... +``` + + +### Available categories + +Flowsint currently organizes types into these standard categories: + +- **Global** contains general-purpose types like Location and Phrase that don't fit neatly into other categories. + +- **Identities & Entities** includes Individual, Username, and Organization for representing people and groups. + +- **Organization** contains Organization for dedicated organizational lookups. + +- **Communication & Contact** covers Phone, Email, Username, SocialAccount, and Message for communication-related data. + +- **Network** encompasses all network-related types including ASN, CIDR, Domain, Website, Ip, Port, DNSRecord, SSLCertificate, and WebTracker. + +- **Security & Access** groups security-relevant types like Credential, Session, Device, Malware, and Weapon. + +- **Files & Documents** contains Document and File for representing digital files. + +- **Financial Data** includes BankAccount and CreditCard for financial information. + +- **Leaks** covers data breach information with the Leak type. + +- **Crypto** contains cryptocurrency-related types including CryptoWallet, CryptoWalletTransaction, and CryptoNFT. + +You can add your type to any of these categories or create a new category if none fit. + + + Registered but uncategorized types + + Some types are registered (via `@flowsint_type`) and used as enricher inputs or outputs, but are intentionally not placed in any built-in category: `Affiliation`, `Alias`, `Breach`, `Gravatar`, `ReputationScore`, `RiskProfile`, `Script`, and `Whois`. They show up in the graph as nodes produced by enrichers (e.g. `Whois` is produced by `domain_to_whois`) but they don't appear in the type picker until you add them to `_get_category_definitions()`. + + + +## Complete examples + +Let' see some complete, real-world examples to illustrate different patterns. + +### Simple type example + +The simplest types have just one or two required fields and minimal complexity: + +```python +from pydantic import Field, model_validator +from typing import Self +from .flowsint_base import FlowsintType +from .registry import flowsint_type + +@flowsint_type +class Hashtag(FlowsintType): + """Represents a social media hashtag.""" + + tag: str = Field( + ..., + description="Hashtag text without the # symbol", + title="Hashtag", + json_schema_extra={"primary": True} + ) + + @model_validator(mode='after') + def compute_label(self) -> Self: + """Compute label for this hashtag.""" + self.nodeLabel = f"#{self.tag}" + return self +``` + +### Type with validation + +This example shows a Social Security Number type with format validation: + +```python +from pydantic import Field, field_validator, model_validator +from typing import Self +from .flowsint_base import FlowsintType +from .registry import flowsint_type +import re + +@flowsint_type +class SocialSecurityNumber(FlowsintType): + """Represents a US Social Security Number.""" + + ssn: str = Field( + ..., + description="Social Security Number in format XXX-XX-XXXX", + title="SSN", + json_schema_extra={"primary": True} + ) + + @field_validator('ssn') + @classmethod + def validate_ssn_format(cls, v: str) -> str: + """Validate SSN format and normalize to standard format.""" + clean = v.replace("-", "").replace(" ", "") + + if not re.match(r"^\d{9}$", clean): + raise ValueError( + "SSN must be exactly 9 digits (format: XXX-XX-XXXX or XXXXXXXXX)" + ) + + return f"{clean[:3]}-{clean[3:5]}-{clean[5:]}" + + @model_validator(mode='after') + def compute_label(self) -> Self: + """Compute label for this SSN.""" + # Mask most digits for privacy + self.nodeLabel = f"SSN ***-**-{self.ssn[-4:]}" + return self +``` + +### Type with related types + +This example shows how types can reference other types to build rich data models: + +```python +from pydantic import Field, model_validator +from typing import Optional, Self +from .flowsint_base import FlowsintType +from .registry import flowsint_type +from .email import Email +from .domain import Domain + +@flowsint_type +class Whois(FlowsintType): + """Represents WHOIS domain registration information.""" + + domain: Domain = Field( + ..., + description="Domain", + title="Domain", + ) + + registrar: Optional[str] = Field( + None, + description="Name of the domain registrar", + title="Registrar" + ) + + email: Optional[Email] = Field( + None, + description="Contact email address from WHOIS record", + title="Contact Email" + ) + + creation_date: Optional[str] = Field( + None, + description="Date when the domain was first registered", + title="Creation Date" + ) + + expiration_date: Optional[str] = Field( + None, + description="Date when the domain registration expires", + title="Expiration Date" + ) + + @model_validator(mode='after') + def compute_label(self) -> Self: + """Compute label for this WHOIS record.""" + if self.registrar: + self.nodeLabel = f"{self.domain.domain} (via {self.registrar})" + else: + self.nodeLabel = f"WHOIS: {self.domain.domain}" + return self +``` + +### Complex type with collections + +This example demonstrates a type with lists of other types and rich metadata: + +```python +from pydantic import Field, model_validator +from typing import Optional, List, Dict, Any, Self +from .flowsint_base import FlowsintType +from .registry import flowsint_type +from .individual import Individual +from .address import Location + +@flowsint_type +class Organization(FlowsintType): + """Represents an organization with comprehensive business information.""" + + name: str = Field( + ..., + description="Legal name of the organization", + title="Organization Name", + json_schema_extra={"primary": True} + ) + + registration_number: Optional[str] = Field( + None, + description="Official business registration number", + title="Registration Number" + ) + + headquarters: Optional[Location] = Field( + None, + description="Primary headquarters location", + title="Headquarters" + ) + + executives: List[Individual] = Field( + default_factory=list, + description="List of company executives and board members", + title="Executives" + ) + + locations: List[Location] = Field( + default_factory=list, + description="All office and facility locations", + title="Locations" + ) + + employee_count: Optional[int] = Field( + None, + description="Total number of employees", + title="Employee Count" + ) + + revenue: Optional[float] = Field( + None, + description="Annual revenue in USD", + title="Revenue" + ) + + industry: Optional[str] = Field( + None, + description="Primary industry sector", + title="Industry" + ) + + metadata: Dict[str, Any] = Field( + default_factory=dict, + description="Additional metadata and custom fields", + title="Metadata" + ) + + @model_validator(mode='after') + def compute_label(self) -> Self: + """Compute label for this organization.""" + if self.industry: + self.nodeLabel = f"{self.name} ({self.industry})" + else: + self.nodeLabel = self.name + return self +``` + +## Best practices and common patterns + +### Documentation + +Keep documentation at the forefront. Every type should have: +- A clear docstring explaining what it represents +- A descriptive `description` parameter for each field (for API docs) +- A meaningful `title` parameter for each field (for UI labels) + +Future developers (including yourself) will thank you for this clarity. + +### Required vs optional fields + +Think carefully about what should be required versus optional: +- **Required fields** (using `...`): Only fields that uniquely identify an entity or are absolutely essential +- **Optional fields** (using `Optional[Type]` and `None`): Most other fields should be optional since intelligence gathering is incremental and you rarely have complete information upfront + +### Always inherit from FlowsintType and use the decorator + +Never inherit directly from Pydantic's `BaseModel`. Always use `FlowsintType` and the `@flowsint_type` decorator: + +```python +# Correct +from .flowsint_base import FlowsintType +from .registry import flowsint_type + +@flowsint_type +class MyType(FlowsintType): + ... + +# Wrong - missing decorator +from .flowsint_base import FlowsintType + +class MyType(FlowsintType): # Not registered! + ... + +# Wrong - wrong base class +from pydantic import BaseModel + +class MyType(BaseModel): # Missing FlowsintType features + ... +``` + +### Always implement compute_label + +Every type must implement a `compute_label` method to set the `nodeLabel` displayed in the UI and graph: + +```python +@model_validator(mode='after') +def compute_label(self) -> Self: + """Compute a human-readable label.""" + # Handle None values gracefully + if self.optional_field: + self.nodeLabel = f"{self.primary_field} ({self.optional_field})" + else: + self.nodeLabel = self.primary_field + return self +``` + +**Best practices for labels:** +- Keep them concise but informative +- Handle None values for optional fields gracefully +- Put the most important information first +- Think about what users need to see at a glance on the graph + +### Type hints and validation + +Use type hints everywhere. They provide: +- Automatic validation +- Better IDE support and autocomplete +- Inline documentation +- Runtime type checking via Pydantic + +For mutable default values like lists and dictionaries, always use `default_factory`: + +```python +# Correct +tags: List[str] = Field(default_factory=list) +metadata: Dict[str, Any] = Field(default_factory=dict) + +# Wrong - all instances will share the same object! +tags: List[str] = Field(default=[]) +metadata: Dict[str, Any] = Field(default={}) +``` + +### Importing other types + +When referencing other Flowsint types, use relative imports to avoid circular import issues: + +```python +# Correct +from .email import Email +from .phone import Phone + +# Avoid +from flowsint_types import Email, Phone # Can cause circular imports +``` + +If you encounter circular import problems, you can use forward references (strings) in type hints and call `model_rebuild()` at the end of your module. + +### Custom validation + +Consider adding custom validators for complex validation logic that goes beyond simple type checking: + +```python +@field_validator('email') +@classmethod +def validate_email(cls, v: str) -> str: + """Validate and normalize email format.""" + if not is_valid_email(v): + raise ValueError("Invalid email format") + return v.lower() +``` + +This keeps validation logic close to the type definition and ensures data integrity throughout the system. + +### Order of execution + +Remember the order in which Pydantic processes your type: +1. **Field validators** (`@field_validator`) run first, validating and potentially transforming individual fields +2. **Model validators** (`@model_validator`) run after, operating on the entire validated model +3. Your `compute_label` method (a model validator) runs last, after all fields are validated + +This means you can safely access validated field values in `compute_label`. + +## Testing your type + +Writing tests for your types ensures they work correctly and helps catch bugs early. Create a test file in `flowsint-types/tests/` that matches your type filename. + +### Basic test structure + +```python +# flowsint_types/tests/test_vehicle.py +from flowsint_types import Vehicle +import pytest + +def test_vehicle_creation(): + """Test creating a vehicle with required fields.""" + vehicle = Vehicle(license_plate="ABC123") + assert vehicle.license_plate == "ABC123" + +def test_vehicle_with_optional_fields(): + """Test creating a vehicle with optional fields.""" + vehicle = Vehicle( + license_plate="ABC123", + brand="Toyota", + model="Camry", + year=2020 + ) + assert vehicle.brand == "Toyota" + assert vehicle.year == 2020 + +def test_vehicle_missing_required_field(): + """Test that validation fails without required fields.""" + with pytest.raises(ValueError): + Vehicle() # Should fail - missing required field +``` + +### Testing label computation + +The label is crucial for UI display, so test it thoroughly: + +```python +def test_vehicle_label_basic(): + """Test label computation with only required fields.""" + vehicle = Vehicle(license_plate="ABC123") + assert vehicle.nodeLabel == "ABC123" + +def test_vehicle_label_with_details(): + """Test label computation with optional fields.""" + vehicle = Vehicle( + license_plate="ABC123", + brand="Toyota", + model="Camry", + year=2020 + ) + assert vehicle.nodeLabel == "ABC123 (Toyota Camry 2020)" + +def test_vehicle_label_partial_details(): + """Test label computation with some optional fields.""" + vehicle = Vehicle( + license_plate="ABC123", + brand="Toyota" + ) + # Should handle None values gracefully + assert vehicle.nodeLabel == "ABC123" +``` + +### Testing field validators + +If your type has custom validators, test both valid and invalid inputs: + +```python +# tests/test_username.py +from flowsint_types import Username +import pytest + +def test_username_valid(): + """Test valid username creation.""" + username = Username(value="john_doe") + assert username.value == "john_doe" + assert username.nodeLabel == "john_doe" + +def test_username_validation_too_short(): + """Test that usernames under 3 characters are rejected.""" + with pytest.raises(ValueError, match="Must be 3-80 characters"): + Username(value="ab") + +def test_username_validation_invalid_chars(): + """Test that invalid characters are rejected.""" + with pytest.raises(ValueError, match="only letters, numbers, underscores, and hyphens"): + Username(value="john@doe") + +def test_username_validation_boundaries(): + """Test boundary conditions.""" + # Minimum length + username = Username(value="abc") + assert username.value == "abc" + + # Maximum length + long_name = "a" * 80 + username = Username(value=long_name) + assert username.value == long_name + + # Too long + with pytest.raises(ValueError): + Username(value="a" * 81) +``` + +### Testing types with nested objects + +When your type contains other Flowsint types, test the relationships: + +```python +# tests/test_social_account.py +from flowsint_types import SocialAccount, Username +import pytest + +def test_social_account_creation(): + """Test creating a social account with a username object.""" + username = Username(value="john_doe") + account = SocialAccount( + username=username, + platform="twitter", + profile_url="https://twitter.com/john_doe" + ) + + assert account.username.value == "john_doe" + assert account.platform == "twitter" + assert account.id == "john_doe@twitter" + +def test_social_account_label_with_display_name(): + """Test label computation with display name.""" + username = Username(value="john_doe") + account = SocialAccount( + username=username, + platform="twitter", + display_name="John Doe" + ) + + assert account.nodeLabel == "John Doe (@john_doe)" + +def test_social_account_label_without_display_name(): + """Test label computation without display name.""" + username = Username(value="john_doe") + account = SocialAccount( + username=username, + platform="twitter" + ) + + assert account.nodeLabel == "@john_doe" +``` + +### Testing serialization + +Verify that your types serialize correctly to JSON: + +```python +def test_vehicle_serialization(): + """Test that vehicle serializes to JSON correctly.""" + vehicle = Vehicle( + license_plate="ABC123", + brand="Toyota", + model="Camry", + year=2020 + ) + + # Convert to dict + data = vehicle.model_dump() + assert data["license_plate"] == "ABC123" + assert data["brand"] == "Toyota" + assert data["nodeLabel"] == "ABC123 (Toyota Camry 2020)" + + # Convert to JSON string + json_str = vehicle.model_dump_json() + assert "ABC123" in json_str + +def test_vehicle_deserialization(): + """Test creating vehicle from dictionary.""" + data = { + "license_plate": "ABC123", + "brand": "Toyota", + "model": "Camry", + "year": 2020 + } + + vehicle = Vehicle(**data) + assert vehicle.license_plate == "ABC123" + assert vehicle.nodeLabel == "ABC123 (Toyota Camry 2020)" +``` + +### Running the tests + +To run your tests: + +```bash +cd flowsint-types +poetry run pytest tests/test_vehicle.py -v + +# Run all tests +poetry run pytest -v + +# Run with coverage +poetry run pytest --cov=flowsint_types tests/ +``` + +### Best practices for testing + +- **Test the happy path first**: Basic creation with valid data +- **Test validation**: Both valid and invalid inputs +- **Test edge cases**: Empty strings, very long strings, boundary values +- **Test label computation**: With and without optional fields +- **Test serialization**: To/from dict and JSON +- **Use descriptive test names**: The test name should describe what it tests +- **Use pytest fixtures** for complex setup that's reused across tests + +Example with fixtures: + +```python +import pytest +from flowsint_types import Username, SocialAccount + +@pytest.fixture +def sample_username(): + """Fixture providing a sample username.""" + return Username(value="john_doe") + +@pytest.fixture +def sample_account(sample_username): + """Fixture providing a sample social account.""" + return SocialAccount( + username=sample_username, + platform="twitter", + profile_url="https://twitter.com/john_doe" + ) + +def test_with_fixtures(sample_account): + """Test using fixtures.""" + assert sample_account.username.value == "john_doe" + assert sample_account.platform == "twitter" +``` + +## Troubleshooting common issues + +### Import errors + +If you encounter import errors after creating your type, make sure you've run `poetry install` in the `flowsint-types` directory. The package needs to be reinstalled for changes to take effect: + +```bash +cd flowsint-types +poetry install +``` + +### Type not appearing in the API + +If your type doesn't appear in the API, verify that you've: +1. Decorated it with `@flowsint_type` +2. Imported it in `flowsint_types/__init__.py` +3. Added it to the `__all__` list in `flowsint_types/__init__.py` +4. Added it to the appropriate category in `_get_category_definitions()` in `flowsint-core/src/flowsint_core/core/services/type_registry_service.py` + +### Type not found in TYPE_REGISTRY + +If `TYPE_REGISTRY.get("MyType")` returns `None`: +- Ensure the `@flowsint_type` decorator is applied to the class +- Ensure the module is imported (either in `__init__.py` or via `load_all_types()`) +- Check for import errors in your type file that prevent the module from loading + +### Validation errors + +For validation errors, check that you're using: +- The ellipsis (`...`) for required fields +- `None` for optional fields +- `Optional[Type]` in type hints for optional fields + +### Nodes not appearing in the graph + +If your type's instances aren't appearing in Neo4j: +- **Check the enricher**: Verify that enrichers using this type call `self.create_node(instance)` +- **Check the created node**: Make sure the format of the created node is correct, no missing required field, etc. + +### Label not appearing correctly + +If labels aren't displaying correctly in the UI or graph: +- **Missing compute_label**: Ensure you've implemented the `@model_validator(mode='after')` method +- **Wrong field name**: Make sure you set `self.nodeLabel`, not `self.label` +- **Not returning Self**: The method must return `self` +- **None handling**: Check that you handle None values for optional fields gracefully +- **Method name**: The method must be named `compute_label` exactly + +### Circular imports + +If you're seeing issues with circular imports: +- Use relative imports (`from .email import Email`) instead of absolute imports +- Use forward references (string type hints) if needed +- Call `model_rebuild()` at the end of your module to resolve forward references + +### Enricher errors with your type + +If enrichers fail when using your type: +- **Validation failures**: Your field validators might be too strict; check validator error messages in logs +- **Nested object issues**: When passing nested Flowsint types, pass the complete object, don't recreate it +- **Primary key extraction**: The graph service needs to extract a primitive value from your primary field + +## Next steps + +Once you've created and registered your type, you can use it in enrichers to build intelligence gathering workflows. Types serve as the input and output specifications for enrichers, and they define the structure of nodes in the Neo4j graph database. + +### Key checklist for new types + +Before considering your type complete, verify that you've: + +- Decorated with `@flowsint_type` +- Inherited from `FlowsintType` +- Marked exactly one field as primary with `json_schema_extra={"primary": True}` +- Implemented `compute_label` method that sets `self.nodeLabel` and handles None values gracefully +- Provided `description` and `title` for all fields +- Used `default_factory` for list and dict fields +- Written tests for creation, validation, primary field, and label computation +- Exported your type in `flowsint_types/__init__.py` +- Added it to a category in `flowsint-core/src/flowsint_core/core/services/type_registry_service.py` +- Run `poetry install` to make the type available + +### Exploring further + +You might also want to explore: + +- **Creating enrichers**: Use your type as input/output in custom enrichers +- **Custom types via API**: Flowsint supports runtime type creation using JSON Schema (see `flowsint-core/src/flowsint_core/core/models.py`) +- **Graph format**: Learn about the [node and edge format](/docs/developers/graph-format) used in the frontend +- **Type schemas**: Understand how Pydantic schemas are used for API validation + +### Final thoughts + +Remember that types are the foundation of everything in Flowsint: +- **Well-designed types** make enrichers easier to write +- **Clear primary fields** ensure proper node identification in the graph +- **Meaningful labels** make the UI and graph database more intuitive +- **Thorough validation** ensures data integrity throughout the platform + +With these concepts mastered, you're ready to create powerful, robust types that will make the entire Flowsint platform more effective for intelligence gathering. diff --git a/docs/getting-started/enrichers.mdx b/docs/getting-started/enrichers.mdx new file mode 100644 index 0000000..ad71134 --- /dev/null +++ b/docs/getting-started/enrichers.mdx @@ -0,0 +1,53 @@ +--- +title: "Enrichers" +description: "Quick start guide to using Enrichers for your OSINT investigations." +category: "Getting started" +order: 4 +author: "Flowsint Team" +tags: ["tutorial", "getting-started", "enrichers"] +version: "1.2.8" +last_updated_at: "2026-05-15" +--- + +### What is an Enricher? + +An enricher is an operation that, starting from an input element A (source entity), produces one or more elements B (target entities) by applying a search or correlation method called a pivot. + +Example: + +```bash +A = my.domain.com (domain name) + ↓ +p = “DNS resolution” (pivot) + ↓ +B = 12.23.34.45 (IP address) +``` + +That said, a pivot is the method or technical process used to derive B from A. The pivot defines how the transformation obtains its result (e.g., DNS resolution, WHOIS lookup, API query, etc.). + +Example: + +```bash +DNS Resolution → domain → IP + ↓ +WHOIS Lookup → IP → owner + ↓ +Reverse Image Search → image → web pages containing that image +``` + +Flowsint comes with a bunch of prebuilt enrichers, divided into multiple categories. Those enrichers can use standard pivots that your machine can support by default (DNS resolution, WHOIS request, etc.) and some other that depend on external tools. + +Those can be : + +- Native : DNS resolutions, Whois, etc. +- Docker tools: [subfinder](https://github.com/projectdiscovery/subfinder), [asnmap](https://github.com/projectdiscovery/asnmap), etc. +- Python tools: [sherlock](https://github.com/sherlock-project/sherlock), [maigret](https://github.com/soxoj/maigret), [reconurge/recontrack](https://github.com/reconurge/recontrack), [reconurge/reconcrawl](https://github.com/reconurge/reconcrawl), [reconurge/reconspread](https://github.com/reconurge/reconspread), etc. +- External services (paid or free): [shodan](https://www.shodan.io/), [whoxy](https://www.whoxy.com/), [whoisxmlapi](https://www.whoisxmlapi.com), etc. + +### Making your own enrichers + +Creating your own enrichers invloves multiple steps, but is not that trivial. + +If you plan on writting your own enrichers and think they could help the community, please contribute by making a pull request ! + +Please refer to [this section](/docs/developers/managing-enrichers) to start building your own enrichers. diff --git a/docs/getting-started/flows.mdx b/docs/getting-started/flows.mdx new file mode 100644 index 0000000..d33951f --- /dev/null +++ b/docs/getting-started/flows.mdx @@ -0,0 +1,159 @@ +--- +title: "Flows" +description: "Quick start guide to using Flows for your OSINT investigations." +category: "Getting started" +order: 5 +author: "Flowsint Team" +tags: ["tutorial", "getting-started", "flows"] +version: "1.2.8" +last_updated_at: "2026-05-15" +--- + +### What are Flows? + +Flows are the chaining of multiple enrichers, where the output of one becomes the input of the next, allowing an investigation to be broadened or deepened. + +Some enrichers can be chained together, to that they can provide a reproductible and scalable research flow that can be re-applied to other entities of the same type. + +### Getting started with Flows + +The best way to get started with flows is to go to [http://localhost:5173/dashboard/flows](http://localhost:5173/dashboard/flows) and create a new flow. + +From that, you can start building your first flow; a flow consists of **one** input type, and multiple chained enrichers. + +Start by drag & dropping your input type to the canva and start using the "**+**" button to add more enrichers to your flow. + +Once you're satisfied with the flow, you can start viewing the execution order by pressing the "**compute**" button. + +Make sure you give it a descriptive name and save ! (`crtl + s` or presse the save button). + +Once it's done, go back to one of your sketches, right click on an item of the same type of the flow, and you should be able to launch it from the "flows" section. + +### Flow schema + +Every time a flow is launched, a log file is created at `flowsint_core/enricher_logs`. + +```json +{ + "sketch_id": "6aa808e4-1360-4c4a-b94f-4bed6c914836", + "scan_id": "52ba38a2-3f2c-4c8b-a7a5-42656f8fb845", + "created_at": "2025-10-26T15:57:52.243549", + "updated_at": "2025-10-26T15:57:52.424052", + "status": "completed", + "enricher_branches": [ + { + "id": "branch-0", + "name": "Main Flow", + "steps": [ + { + "nodeId": "Domain-1761469976169", + "params": {}, + "type": "type", + "inputs": {}, + "outputs": { + "domain": [ + "example.com" + ] + }, + "status": "pending", + "branchId": "branch-0", + "depth": 0 + }, + { + "nodeId": "domain_to_ip-1761469978018", + "params": {}, + "type": "enricher", + "inputs": { + "Domain": null + }, + "outputs": { + "address": "example.com", + "latitude": "example.com", + "longitude": "example.com", + "country": "example.com", + "city": "example.com", + "isp": "example.com" + }, + "status": "pending", + "branchId": "branch-0", + "depth": 1 + } + ] + } + ], + "execution_log": [ + { + "step_id": "branch-0_domain_to_ip-1761469978018", + "branch_id": "branch-0", + "branch_name": "Main Flow", + "node_id": "domain_to_ip-1761469978018", + "enricher_name": "domain_to_ip", + "inputs": [ + "example.com" + ], + "outputs": [ + { + "address": "12.34.56.78", + "latitude": null, + "longitude": null, + "country": null, + "city": null, + "isp": null + } + ], + "status": "completed", + "error": null, + "timestamp": "2025-10-26T15:57:52.274147", + "execution_time_ms": 144, + "cache_hit": false + } + ], + "summary": { + "total_steps": 1, + "completed_steps": 1, + "failed_steps": 0, + "total_execution_time_ms": 144 + }, + "final_results": { + "initial_values": [ + "example.com" + ], + "branches": [ + { + "id": "branch-0", + "name": "Main Flow", + "steps": [ + { + "nodeId": "domain_to_ip-1761469978018", + "enricher": "domain_to_ip", + "status": "completed", + "outputs": [ + { + "address": "12.34.56.78", + "latitude": null, + "longitude": null, + "country": null, + "city": null, + "isp": null + } + ] + } + ] + } + ], + "results": { + "domain_to_ip-1761469978018": [ + { + "address": "12.34.56.78", + "latitude": null, + "longitude": null, + "country": null, + "city": null, + "isp": null + } + ] + }, + "reference_mapping": {} + } +} +``` diff --git a/docs/getting-started/quickstart.mdx b/docs/getting-started/quickstart.mdx new file mode 100644 index 0000000..ec449c0 --- /dev/null +++ b/docs/getting-started/quickstart.mdx @@ -0,0 +1,42 @@ +--- +title: "Installation" +description: "Quick start guide to using Flowsint for your OSINT investigations." +category: "Getting started" +order: 3 +author: "Flowsint Team" +tags: ["tutorial", "quickstart", "installation"] +version: "1.2.8" +last_updated_at: "2026-05-15" +--- + +### Prerequisites + +Before installing Flowsint, ensure you have the following installed on your system: + +- **Docker** and **Docker Compose** +- **Make** (for build automation) +- **Git** + +### Installation + +Clone the repo and run the start command. + +```bash +git clone https://github.com/reconurge/flowsint.git +cd flowsint +make prod +``` + +Some enrichers require API keys. Check out [this section](/docs/getting-started/enrichers#api-keys) to learn more. + +The application should automatically open at http://localhost:5173. + +### Create your first investigation + +Start by logging in or registering from the home page. From your dashboard, create a new investigation by clicking "New investigation." Add your first entity—such as a domain name—to the canvas. Right-click the entity to open the context menu and run an enricher. As results appear, explore the newly discovered entities and relationships directly in the graph. + +### Running your first enricher + +You could start by discovering subdomains for a domain for example. + +Add a domain entity like `example.com` to your investigation, then right-click the domain node and select the "domain_to_subdomains" enricher. Wait for the enricher to complete; newly discovered subdomains will be added to your graph for you to review. diff --git a/docs/getting-started/vault.mdx b/docs/getting-started/vault.mdx new file mode 100644 index 0000000..963053c --- /dev/null +++ b/docs/getting-started/vault.mdx @@ -0,0 +1,58 @@ +--- +title: "Vault" +description: "Quick start guide to using the Vault to secure your services API keys and secrets." +category: "Getting started" +order: 6 +author: "Flowsint Team" +tags: ["tutorial", "getting-started", "vault"] +version: "1.2.8" +last_updated_at: "2026-05-15" +--- + +## What is the Vault + +A good amount of the tools you'll be using in Flowsint require third party API keys. + +The **Vault** (*"Coffre fort"* in french) is the place to centralize and securely store those API keys. +Weither you have a local instance of Flowsint or one fully deployed on a distributed system, you need to have your keys securely stored. + +## Adding a key + +In the Flowsint enricher ecosystem, the API keys follow a specific format, being in uppercase letters, and with a declarative name that follows `_API_KEY`. + +## Current limitations + +For now, we cannot match a particular key from the Vault to an enricher **directly from the UI**. The enricher declares the API key variable name it requires, like the following in the core of the Enricher: + +```python +@classmethod + def get_params_schema(cls) -> List[Dict[str, Any]]: + """Declare required parameters for this enricher""" + return [ + { + "name": "PDCP_API_KEY", + "type": "vaultSecret", + "description": "The ProjectDiscovery Cloud Platform API key for asnmap.", + "required": True, + }, + ] +``` + +This is a known limitation and we are working on improving this. + +In the meanwhile, here is a list of the needed keys to run Flowsint at it's full potential: + +```bash +# for enrichers +WHOXY_API_KEY # Whoxy domain search engine [WHOXY] +PDCP_API_KEY # ProjectDiscovery Cloud Platform [ASNMAP], [NAABU] etc +HIBP_API_KEY # HaveIBeenPwned API key [HIBP] +ETHERSCAN_API_KEY # Etherscan crypto API key [ETHERSCAN] +# for Flo, AI assistant +MISTRAL_API_KEY +# but other providers will be supported soon (ChatGPT, etc.) +``` + +There are also some other tools that could need a bunch of other API keys like [Subfinder](https://github.com/projectdiscovery/subfinder). Configuring them is not possible for now, but will be soon. + +Stay tuned for updates as those mechanisms may vary in the future, as the goal is to keep the user experience as smooth as possible. diff --git a/docs/overview.mdx b/docs/overview.mdx new file mode 100644 index 0000000..f3898d3 --- /dev/null +++ b/docs/overview.mdx @@ -0,0 +1,59 @@ +--- +title: "Welcome to Flowsint" +description: "Complete documentation for Flowsint - a modular OSINT investigation platform." +category: "Overview" +order: 1 +author: "Flowsint Team" +tags: ["documentation", "overview", "getting-started"] +version: "1.2.8" +last_updated_at: "2026-05-15" +--- + +### What is Flowsint? + +Flowsint is a modular investigation and reconnaissance platform focused on OSINT (Open Source Intelligence). It provides: + +- Graph-based visualization of entity relationships +- 30+ automated enrichers for intelligence gathering +- Modular architecture with clean separation of concerns +- Privacy-first design with local data storage +- Extensible platform for custom enrichers +- Automated search flows (more on that [here](/docs/getting-started/flows)) + + + Disclaimer ! + + The author(s) and contributor(s) of this tool assume no responsibility or liability for any damages, losses, or consequences that may result from the use or misuse of this software. + By using this tool, you acknowledge and agree that: + - You are solely responsible for your use of this software + - You will use this tool in compliance with all applicable laws and regulations + - You will obtain proper authorization before conducting any security testing or reconnaissance activities + - You understand the potential risks and legal implications of using security tools + + + +### Why Flowsint? + +If you've already practiced some OSINT, you know that analysts often rely on a multitude of research tools: scripts, third-party services, specialized applications. But these tools often work **in silos** and quickly become obsolete if they're not maintained: a service disappears, an API changes, an access point closes. The analyst juggles with unstable tools and sometimes has to **manually adapt their data** to continue their investigation. + +OSINT tools, for most, are **consumables**: they evolve, appear, and disappear. Research methods change, security mechanisms evolve. However, the fundamental need always remains the same: **to see, exploit, and analyze data in a clear and understandable way**. Analysts need to be able to list, centralize, and visualize connections to have a clear understanding of their investigation. + +This is exactly what Flowsint was built for: a solid and durable foundation on which your investigations rest. Tools become simple extensions that plug in and unplug easily. A new tool comes out, and with a few manipulations it can be integrated into your investigation workflow. + +**Flowsint is the stable infrastructure that allows you to stay agile in the face of constant evolution of methods and sources.** + +Flowsint is a local tool, running on your machine only. This ensures a great level of confidentiality, but comes with responsabilities. + + + At your own risk + + All enrichers run locally on your machine. This means you can get banned from some services or get flagged from infrastructures if you start making thousands of requests to the same service. + You need to always know what you are doing, and understand that gathering can go very fast in scale. + + For example, you can very easily happen to be making DNS resolution requests for 10 000 IPs. + + Know you infrastructure and your limits. Know how the tools used in the enrichers actually work. You can have a list of the available enrichers and tools [here](/docs/sources/available-enrichers). + + + +If all those points are clear for you, let's start investigating ! diff --git a/docs/sources/available-enrichers.mdx b/docs/sources/available-enrichers.mdx new file mode 100644 index 0000000..93abe65 --- /dev/null +++ b/docs/sources/available-enrichers.mdx @@ -0,0 +1,163 @@ +--- +title: "Enrichers catalog" +description: "Quick start guide to using Enrichers for your OSINT investigations." +category: "Sources" +order: 11 +author: "Flowsint Team" +tags: ["tutorial", "getting-started", "enrichers"] +version: "1.2.8" +last_updated_at: "2026-05-15" +--- + +### ASN +**asn_to_cidrs**: Given an ASN, enumerate its announced CIDR ranges. +Tools/Pivots: [asnmap](https://github.com/projectdiscovery/asnmap) (CLI), [jq](https://jqlang.github.io/jq/) (CLI) + +### CIDR +**cidr_to_ips**: Expand a CIDR to IPs by PTR enumeration heuristics. +Tools/Pivots: [dnsx](https://github.com/projectdiscovery/dnsx) (CLI) + +### Crypto +**cryptowallet_to_transactions**: Fetch ETH wallet transactions and map wallet-to-wallet relationships. +Tools/APIs: [Etherscan API](https://docs.etherscan.io/) + +**cryptowallet_to_nfts**: Fetch ERC-721/1155 NFT transfers for a wallet. +Tools/APIs: [Etherscan API](https://docs.etherscan.io/) + +### Domain +**domain_to_ip**: Resolve domains to IPv4 addresses. +Tools/Pivots: DNS resolution (socket) + +**domain_to_subdomains**: Discover subdomains for a domain. +Tools/APIs: [subfinder](https://github.com/projectdiscovery/subfinder) (CLI), fallback to [crt.sh JSON API](https://crt.sh/?output=json) + +**domain_to_whois**: Retrieve WHOIS registration data for a domain. +Tools/APIs: [python-whois](https://pypi.org/project/python-whois/) + +**domain_to_asn**: Map a domain to its ASN by resolving and querying ASN data. +Tools/Pivots: system DNS, [asnmap](https://github.com/projectdiscovery/asnmap) (CLI) + +**domain_to_root_domain**: Convert a subdomain to its registrable root. +Tools/Pivots: internal domain utils + +**domain_to_history**: Retrieve historical WHOIS records and extract related entities (individuals, organizations, emails, phones, locations). +Tools/APIs: [Whoxy API](https://www.whoxy.com/api/) + +**domain_to_website**: Convert a domain to a reachable website URL (HTTP/HTTPS), following redirects. +Tools/Pivots: HTTP HEAD requests + +**domain_to_tls**: Retrieve TLS/SSL certificate information for a domain. +Tools/Pivots: [httpx](https://github.com/projectdiscovery/httpx) (CLI) + +**domain_to_whois_history**: Retrieve historical WHOIS records for a domain and extract related entities (individuals, organizations, emails, locations). +Tools/APIs: [WhoisXML API](https://whois.whoisxmlapi.com/) + +**domain_to_dehashed**: Get breach intelligence (credentials, related individuals) associated with a domain. +Tools/APIs: [DeHashed API](https://www.dehashed.com/docs) + +### Email +**email_to_breaches**: Check whether an email appears in known breaches. +Tools/APIs: [Have I Been Pwned API](https://haveibeenpwned.com/API/v3) + +**email_to_gravatar**: Check Gravatar existence and profile for an email (via MD5 hash). +Tools/APIs: [Gravatar endpoints](https://en.gravatar.com/site/implement/images/) + +**email_to_domain**: Extract the domain part of an email address. +Tools/Pivots: internal email parser + +**email_to_domains**: Find domains registered by a given email address; extract related contacts and entities. +Tools/APIs: [Whoxy API](https://www.whoxy.com/api/) + +**email_to_username**: Extract the local-part of an email as a Username entity. +Tools/Pivots: internal email parser + +**email_to_intelligence**: Get breach intelligence (credentials, related individuals) associated with an email. +Tools/APIs: [DeHashed API](https://www.dehashed.com/docs) + +**email_to_device_hudsonrock**: Look up devices compromised by infostealers and associated with an email. +Tools/APIs: [HudsonRock API](https://www.hudsonrock.com/) + +### Individual +**individual_to_domains**: Find domains registered by a specific person; extract related contacts and attributes. +Tools/APIs: [Whoxy API](https://www.whoxy.com/api/) + +**individual_to_organization**: Find organizations related to a person in French registries. +Tools/APIs: SIRENE (via internal SireneTool) — see [INSEE Sirene API](https://api.insee.fr/catalogue/#/datasets/sirene) + +### IP +**ip_to_domain**: Reverse-resolve IPs to domains via PTR and Certificate Transparency pivots. +Tools/APIs: DNS PTR (socket), [crt.sh JSON API](https://crt.sh/?output=json) + +**ip_to_infos**: Enrich IPs with geolocation and ISP data. +Tools/APIs: [ip-api.com](https://ip-api.com/) + +**ip_to_asn**: Map IPs to their ASN. +Tools/Pivots: AsnmapTool ([asnmap](https://github.com/projectdiscovery/asnmap)) + +**ip_to_ports**: Scan an IP for open ports and services. +Tools/Pivots: [naabu](https://github.com/projectdiscovery/naabu) (CLI) + +**ip_to_fraudscore**: Compute a fraud risk score for an IP address. +Tools/APIs: [Scamalytics API](https://scamalytics.com/ip-api) + +**ip_to_intelligence**: Get breach intelligence (credentials, related individuals) associated with an IP. +Tools/APIs: [DeHashed API](https://www.dehashed.com/docs) + +### Organization +**org_to_domains**: Find domains registered by an organization; extract contacts and related entities. +Tools/APIs: [Whoxy API](https://www.whoxy.com/api/) + +**org_to_infos**: Enrich organizations with French registry data and leaders. +Tools/APIs: SIRENE (SireneTool) — see [INSEE Sirene API](https://api.insee.fr/catalogue/#/datasets/sirene) + +**org_to_asn**: Find ASNs associated with an organization name. +Tools/Pivots: [asnmap](https://github.com/projectdiscovery/asnmap) (CLI), [jq](https://jqlang.github.io/jq/) (CLI) + +### Phone +**phone_to_infos**: Probe phone footprint across services (demo modules) and normalize number. +Tools/APIs: ignorant modules (Amazon, Snapchat, Instagram), [httpx](https://github.com/projectdiscovery/httpx) + +**phone_to_carrier**: Look up carrier, country, and validity metadata for a phone number. +Tools/APIs: [Veriphone API](https://veriphone.io/) + +**phone_to_device_hudsonrock**: Look up devices compromised by infostealers and associated with a phone number. +Tools/APIs: [HudsonRock API](https://www.hudsonrock.com/) + +### Social +**username_to_socials_sherlock**: Enumerate social accounts for a username using Sherlock. +Tools/Pivots: [sherlock](https://github.com/sherlock-project/sherlock) (CLI) + +**username_to_socials_maigret**: Enumerate social accounts for a username using Maigret and parse rich metadata. +Tools/Pivots: [maigret](https://github.com/soxoj/maigret) (CLI) + +**username_to_dehashed**: Get breach intelligence (credentials, related individuals) associated with a username. +Tools/APIs: [DeHashed API](https://www.dehashed.com/docs) + +**username_to_device_hudsonrock**: Look up devices compromised by infostealers and associated with a username. +Tools/APIs: [HudsonRock API](https://www.hudsonrock.com/) + +### Website +**website_to_crawler**: Crawl a website to extract emails and phone numbers. +Tools/APIs: ReconCrawlTool (`reconcrawl`) + +**website_to_domain**: Extract the domain name from a website URL. +Tools/Pivots: internal URL parser + +**website_to_subdomains**: Find subdomains of a website's domain via external scan. +Tools/APIs: [c99.nl API](https://api.c99.nl/) + +**website_to_links**: Crawl a website and collect internal/external links and domains. +Tools/APIs: reconspread Crawler + +**website_to_text**: Fetch and extract visible text from a webpage. +Tools/APIs: HTTP GET, [BeautifulSoup](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) + +**website_to_webtrackers**: Extract analytics/ads tracking codes from a website. +Tools/APIs: recontrack TrackingCodeExtractor + +--- + +Notes +- Some enrichers optionally depend on docker binaries: `subfinder`, `asnmap`, `dnsx`, `naabu`, `httpx`, and `jq` which are installed in the docker container. +- API-keyed enrichers read keys from params or environment (e.g., `HIBP_API_KEY`, `ETHERSCAN_API_KEY`, `WHOXY_API_KEY`, `WHOISXML_API_KEY`, `DEHASHED_API_KEY`, `SCAMALYTICS_API_KEY`, `VERIPHONE_API_KEY`, `C99_API_KEY`). +- Internal/test enrichers (`domain_to_dummy`, `ip_to_dummy_domains`, `n8n_connector`) are not listed here — they exist in the codebase but are not part of the public catalog. diff --git a/docs/syllabus.mdx b/docs/syllabus.mdx new file mode 100644 index 0000000..37150a3 --- /dev/null +++ b/docs/syllabus.mdx @@ -0,0 +1,73 @@ +--- +title: "Syllabus" +description: "Syllabus, just to make sure we speak the same language. Those definitions apply in the context of Flowsint platform." +category: "Overview" +order: 2 +author: "Flowsint Team" +tags: ["documentation", "overview", "syllabus"] +version: "1.2.8" +last_updated_at: "2026-05-15" +--- + +### OSINT + + Open Source Intelligence consists of collecting, analyzing, and exploiting **freely** and **openly** available information from search engines, images, social networks, public archives, etc. + +### Investigation + + A structured process aimed at collecting, correlating, and analyzing information from different sources and enrichers, in order to answer a question or solve a problem. An investigation can be **exploratory** (discovering unknown elements) or **targeted** (validating a hypothesis). An investigation can contain multiple **sketches** (each representing a different view or stage of the analysis) and one or more **analyses**. + +### Sketch + + Visual result produced by executing one or more enrichers on one or more entities. A sketch represents the current state of the graph derived from collected data at a given moment in the investigation. Multiple sketches can exist for the same investigation to capture different perspectives or stages. + +### Analysis + + Set of processing, interpretations, and verifications performed on data collected during the investigation. Analyses aim to identify trends, confirm or refute hypotheses, and produce actionable conclusions. They can be **quantitative** (measurements, statistics) or **qualitative** (contextual assessments, behavioral patterns). + +### Enricher + + An **enricher** is an operation that, from an input element **A** (*source entity*), allows obtaining one or more elements **B** (*target entities*) by applying a search or correlation method called a **pivot**. + + > Example: + > + > + > A = `my.domain.com` (*domain name*) + > + > p = "DNS resolution" (*pivot*) + > + > B = `12.23.34.45` (*IP address*). + > +### Pivot + + A **pivot** is the method or technical process used to derive **B** from **A**. The pivot defines **how** the enricher obtains its result (e.g., DNS resolution, WHOIS lookup, API query, etc.). + + > Examples of pivots: + > + > DNS Resolution → domain → IP + > WHOIS Lookup → IP → owner + > Reverse Image Search → image → web pages containing this image + +### Tool + + A tool generally refers to a script, program, or service providing a **pivot**, i.e., a means to retrieve or enricher information from an input element. + +### Entity + + An identifiable object or element manipulated by enrichers (e.g., IP address, domain, email address, user identifier, file hash, etc.). An entity is always associated with a **Sketch**. In the graph, entities are represented as **nodes** (see [Graph format](/docs/developers/graph-format) for technical details). + +### Relationship + + Defines a link between two entities. This link is generally named (in uppercase) and can be unidirectional or bidirectional. + + > Examples of relationships: + > + > + > A = `my.domain.com` → `RESOLVES_TO` → `12.23.34.45` + > + + A relationship is always associated between a **source** node (*from*) and a **target** node (*to*). In the graph, relationships are represented as **edges** (see [Graph format](/docs/developers/graph-format) for technical details). + +### Flow + + The chaining of multiple enrichers, where the output of one becomes the input of the next, allowing to expand or deepen an investigation.