> For the complete documentation index, see [llms.txt](https://adatrack.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://adatrack.gitbook.io/docs/documentation/features/plugins.md).

# Plugins & Extensions

The **AdaTrack Plugin System** allows you to extend the platform with custom functionality — without forking the core codebase. Plugins can add new workflow nodes, report blocks, alert channels, dashboard widgets, scheduled jobs, and more. Extensions are managed through the admin UI and can be built in Go (compiled-in) or JavaScript (scripted at runtime).

### Key Capabilities

* **8 Extension Points:** Add custom workflow nodes, report blocks, alert dispatchers, dashboard widgets, HTTP routes, cron jobs, event hooks, and WebSocket channels.
* **Dual Runtime:** Choose between compiled-in Go plugins for maximum performance, or JavaScript (Goja) scripted plugins for rapid development with no recompilation.
* **Admin UI:** Install, enable, disable, configure, health-check, and uninstall plugins from the Plugins tab in the admin panel.
* **Config Encryption:** Sensitive plugin settings (API keys, tokens) marked as `writeOnly` in the plugin's schema are encrypted at rest using AES-256-GCM.
* **Event Hooks:** Plugins can subscribe to platform events (telemetry received, alert fired, geofence transition, workflow executed, report generated) and react in real time.
* **Sandboxed Execution:** Scripted plugins run in an isolated JavaScript VM with no filesystem or network access. Each execution has a configurable timeout.

***

### Extension Points

#### Workflow Nodes

Plugins can register custom node types that appear in the visual workflow editor alongside built-in nodes. A plugin node receives input data and settings, performs its logic, and returns output for downstream nodes.

*Example:* A plugin adds an "AI Anomaly Detection" node that analyzes telemetry patterns and flags outliers.

#### Report Blocks

Plugins can add custom block types to the report generator. Each block renders HTML content that is included in generated PDF reports.

*Example:* A billing plugin adds a "Usage Summary" block showing monthly device counts and API call volumes.

#### Alert Dispatchers

Plugins can register custom notification channels beyond the built-in Webhook, Slack, and Telegram dispatchers.

*Example:* A plugin adds a "PagerDuty" dispatcher that creates incidents when critical alerts fire.

#### Dashboard Widgets

Plugins can provide custom widget types for the interactive dashboard builder. The widget component is rendered inside the dashboard grid alongside built-in widgets.

*Example:* A plugin adds a "Fleet Health Score" widget that displays a composite metric calculated from multiple telemetry sources.

#### HTTP Routes

Plugins can register custom API endpoints under `/api/v1/plugins/{pluginID}/`. These routes are protected by the platform's JWT authentication.

#### Cron Jobs

Plugins can register scheduled tasks that run on a cron schedule (e.g., daily data aggregation, periodic API sync).

#### Event Hooks

Plugins can subscribe to platform lifecycle events and execute logic in response:

| Event                 | Fires When                                                  |
| --------------------- | ----------------------------------------------------------- |
| `telemetry.received`  | A device sends a valid telemetry packet                     |
| `alert.fired`         | An alert rule triggers (geofence or telemetry)              |
| `geofence.transition` | A device enters or exits a geofence                         |
| `workflow.executed`   | A workflow run completes (success or failure)               |
| `report.generated`    | A report finishes generating                                |
| `trip.started`        | A travel log trip begins (speed/distance threshold crossed) |
| `trip.completed`      | A travel log trip ends (stop confirmed)                     |

#### WebSocket Channels

Plugins can register custom WebSocket channels and broadcast real-time messages to connected users.

***

### Built-in Plugins

AdaTrack ships with several official compiled plugins:

| Plugin                  | Description                                                                                                                                                                                                                                                                      | License gate                  |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- |
| **MQTT Broker**         | Embedded MQTT broker for bi-directional device communication. See [MQTT Protocol](/docs/documentation/iot-ingestion/mqtt.md).                                                                                                                                                    | Standard+                     |
| **Codec8**              | TCP ingestion for Teltonika GPS trackers (FMB920, FMT100, FMB140, …) using the Codec8/Codec8E binary protocol. See [Codec8 (Teltonika TCP)](/docs/documentation/iot-ingestion/codec8.md).                                                                                        | Standard+ (`plugin:codec8`)   |
| **Codec8 Telemetry UI** | Dashboard widgets and trip replay telemetry panel for Codec8 devices. Provides Speedometer, Odometer, Satellite Count, Battery Voltage, and Engine Temperature widgets. Auto-enabled with the Codec8 plugin.                                                                     | Standard+ (`plugin:codec8`)   |
| **Queclink**            | TCP ingestion for Queclink GPS trackers (GV58CEU(CG) and other `@Track`-compatible models) using the `@Track Air Interface Protocol`. See [Queclink (@Track TCP)](https://github.com/AdaTrack/adatrack_platform/tree/main/docs/gitbook/documentation/iot-ingestion/queclink.md). | Standard+ (`plugin:queclink`) |
| **Chat Bot**            | Telegram and Slack integration for device queries, trip summaries, and alert notifications. See [Chat Bot](/docs/documentation/features/chatbot.md).                                                                                                                             | Standard+                     |
| **AI Assistant**        | Natural-language fleet queries powered by Claude. Answers questions about devices, trips, and telemetry in plain text. Usage is metered against your plan's monthly [AI Tokens quota](/docs/documentation/administration/quotas.md).                                             | Standard+                     |

***

### Managing Plugins

Navigate to **Admin > Plugins** to manage the plugin lifecycle:

| Action           | Description                                                                                                                                                           |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Enable**       | Initializes the plugin and registers its extension points. The enabled state is persisted to the database and restored automatically on server restart.               |
| **Disable**      | Stops the plugin and removes its registered extensions. The disabled state is persisted — the plugin will not restart automatically after a server restart or deploy. |
| **Configure**    | Opens a form auto-generated from the plugin's config schema                                                                                                           |
| **Health Check** | Runs the plugin's self-diagnostic and reports healthy/unhealthy                                                                                                       |
| **Uninstall**    | Removes the plugin and cleans up all registered extensions                                                                                                            |

Plugin configuration values marked as `writeOnly` (such as API keys) are displayed as masked fields in the admin UI and encrypted at rest when an encryption key is configured.

***

### Scripted Plugins (JavaScript)

Scripted plugins are written in JavaScript (ECMAScript 5.1) and executed in a sandboxed [Goja](https://github.com/nicholasgasior/goja) runtime. They are stored in the database and require no server recompilation.

#### Host API

Scripted plugins have access to the `adatrack` global object with the following namespaces:

| Namespace            | Methods                                                 | Description                                                                                                                                                                                                 |
| -------------------- | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `adatrack.devices`   | `list()`, `get(id)`                                     | Query devices and profiles                                                                                                                                                                                  |
| `adatrack.telemetry` | `latest(deviceId, limit)`                               | Fetch recent telemetry readings                                                                                                                                                                             |
| `adatrack.events`    | `publish(type, payload)`                                | Emit custom events to the event bus                                                                                                                                                                         |
| `adatrack.config`    | `get(key)`                                              | Read the plugin's own configuration                                                                                                                                                                         |
| `adatrack.store`     | `get(key)`, `set(key, value)`                           | Persistent key-value store scoped to the plugin                                                                                                                                                             |
| `adatrack.log`       | `info(msg)`, `error(msg)`                               | Write to the server log                                                                                                                                                                                     |
| `adatrack.ui`        | `registerWidget(def)`, `registerTelemetryRenderer(def)` | Register a dashboard widget or trip replay telemetry panel. Widget definitions declare a `type`, `label`, and `render(reading)` function; telemetry renderers declare a `render(reading, cursor)` function. |

#### Timeout

Each scripted plugin execution has a configurable timeout (default: 1 second). If the script exceeds this limit, the VM is interrupted and the execution returns an error. The timeout is set per-plugin via the plugin's own configuration (`script_timeout_ms`).

***

### Configuration

#### Environment Variables

| Variable                 | Default   | Description                                                                                                                                                       |
| ------------------------ | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PLUGINS_ENABLED`        | `true`    | Master switch for the plugin system                                                                                                                               |
| `PLUGINS_ENCRYPTION_KEY` | *(empty)* | AES-256 encryption key for `writeOnly` config fields. Must be exactly 64 hex characters. Generate with `openssl rand -hex 32`. Leave empty to disable encryption. |

#### Per-Plugin Configuration

Each plugin declares a JSON Schema for its configuration. The admin UI auto-generates a form from this schema supporting text fields, numbers, booleans, dropdowns (enum), and password fields (writeOnly).

Plugin configuration is stored in the database and can be updated at any time via the admin panel. Changes take effect immediately — no server restart required.

***

### Security

* **Sandboxed runtime:** Scripted plugins run in a Goja VM with no access to the filesystem, network, or Go standard library. Only the `adatrack.*` host API is available.
* **Namespaced database access:** Plugins that require database storage get tables prefixed with `plugin_{id}_`. SQL statements are validated to prevent access to platform tables.
* **JWT-protected routes:** Plugin HTTP routes are mounted behind the platform's authentication middleware. Unauthenticated requests are rejected.
* **Error sanitization:** Plugin admin endpoints return generic error messages to clients. Internal errors are logged server-side only.
* **Config encryption:** Sensitive configuration values (API keys, secrets) declared as `writeOnly` in the plugin schema are encrypted with AES-256-GCM before storage. They are masked in API responses.

### Quotas & Limits

* **Script timeout:** Configurable per-plugin (default 1 second). Prevents runaway scripts from blocking worker threads.
* **Memory:** Goja does not enforce memory limits natively. Scripted plugins share the Go process memory. The timeout mechanism provides a practical bound on resource consumption.
* **Extension cleanup:** When a plugin is disabled or uninstalled, all registered extensions (workflow nodes, report blocks, cron jobs, event hooks, etc.) are automatically removed.
