> For the complete documentation index, see [llms.txt](https://support.attackforge.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://support.attackforge.com/app/automations-and-integrations/report-automation.md).

# Report Automation

## Overview

Report automation lets you generate AttackForge reports from your own scripts, pipelines and tools, without anyone generating them by hand.

<figure><img src="https://372186556-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M8s1QY2Q6YTHB4a6DMu%2Fuploads%2FXarZKjbg37lRGFDU0ptj%2Freport-automation-at-a-glance.svg?alt=media&amp;token=5bbba77a-9432-4154-8bbf-d9de207b261f" alt=""><figcaption></figcaption></figure>

ReportGen is a client-side library. Reports are generated on the user's own device, not on AttackForge infrastructure. That has several key benefits:

| Benefit                         | What it means for you                                                                                                                                                                                         |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Security**                    | Reports are never generated on AttackForge servers.                                                                                                                                                           |
| **Scale**                       | Report generation doesn't slow down the application, even when many users generate reports at the same time.                                                                                                  |
| **Data stays in your control**  | The finished report is created on your device or in your own environment, and isn't stored in AttackForge unless you upload it. This helps with data residency, sovereignty and confidentiality requirements. |
| **Tenant isolation**            | Reports aren't built on shared servers, so your templates and findings are never processed alongside another customer's.                                                                                      |
| **Offline and air-gapped use**  | Once you have the report data and template, the CLI or library doesn't need a connection to AttackForge.                                                                                                      |
| **No queues or limits**         | There's no shared report service to wait on. Run as many reports at once as your own infrastructure allows, such as one for every project in a portfolio.                                                     |
| **Faster template development** | Test templates locally with instant feedback, and see `$help` output in your own browser console or logs.                                                                                                     |
| **The same engine everywhere**  | The browser, the CLI and the Node library all use ReportGen, so a template gives the same result whether a person or a pipeline generates the report.                                                         |
| **Your own post-processing**    | Convert to PDF, sign, watermark, scan or archive the report in your environment before it goes anywhere else.                                                                                                 |
| **Version control**             | In automation, pin a ReportGen version and upgrade when you're ready, so reports don't change unexpectedly.                                                                                                   |

Because ReportGen runs where you run it, you can also run it inside your own automation stack. You fetch the project's report data and a report template from the Self-Service API, then combine them with the ReportGen CLI or Node library to produce a DOCX report.

## Why it matters

* **Reports on demand.** Produce reports as soon as testing finishes, on a schedule, or whenever data changes.
* **No manual steps.** Remove the download-and-generate routine from every project.
* **Your data stays with you.** Reports are generated in your environment, using your templates.
* **Fits your tools.** Send finished reports to a document system, ticketing system or client portal.

## Who uses it

| Who                                  | To                                                                  |
| ------------------------------------ | ------------------------------------------------------------------- |
| **Consultancies and MSSPs**          | Generate client reports automatically at the end of each engagement |
| **Internal security teams**          | Produce regular reports for application owners and leadership       |
| **DevSecOps and platform teams**     | Build reports into CI/CD pipelines and scheduled jobs               |
| **Developers and integration teams** | Embed ReportGen in their own applications                           |

## Recommended approach

We recommend the following approach:

1. Download the [ReportGen CLI](https://www.npmjs.com/package/@attackforge/reportgen-cli) or [ReportGen NodeJS library](https://www.npmjs.com/package/@attackforge/reportgen-node).
2. Configure the ReportGen CLI or library to run within your automation stack.
3. When you need to generate a report:
   1. Fetch the [Project Report Data](https://docs.attackforge.com/rest-api/methods/getProjectReportData) from the Self-Service API.
   2. Fetch the [Report Templates](https://docs.attackforge.com/rest-api/methods/getReportTemplates) and [download the Report Template](https://docs.attackforge.com/rest-api/methods/downloadReportTemplate) for your desired report type.
   3. Combine the ReportGen CLI or library, the report template and the report data to produce your report.

The sections below walk through each step.

## Step 1: Choose the CLI or the Node library

Both tools produce the same DOCX report. The CLI wraps the library.

|                 | ReportGen CLI                                                                            | ReportGen Node library                                                                     |
| --------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| **Package**     | [`@attackforge/reportgen-cli`](https://www.npmjs.com/package/@attackforge/reportgen-cli) | [`@attackforge/reportgen-node`](https://www.npmjs.com/package/@attackforge/reportgen-node) |
| **Use it when** | You run reports from shell scripts, CI/CD jobs or scheduled tasks                        | You build report generation into your own Node.js application or service                   |
| **Input**       | File paths for the template, data and output                                             | The template as an `ArrayBuffer`, and the parsed report data                               |
| **Output**      | A DOCX file                                                                              | A `Promise` that resolves to the DOCX as an `ArrayBuffer`                                  |

### Requirements

* Node.js 24.15.0 or later (Node 26+ is also supported).
* The Node library depends on [`canvas`](https://www.npmjs.com/package/canvas) to render charts to PNG. Prebuilt binaries are available for most platforms. On platforms without one, install the native build dependencies for `canvas` first: Cairo, Pango, libjpeg, giflib and librsvg.

## Step 2: Install and configure ReportGen

### ReportGen CLI

Install the CLI globally, so the `reportgen` command is available in your path:

```bash
$ npm -g install @attackforge/reportgen-cli
```

Or run it directly, without installing:

```bash
$ npx @attackforge/reportgen-cli
```

Usage:

```bash
$ reportgen [--output=output_file.docx] [--data=data.json] [--template=template_file.docx] [--quiet]
```

| Option          | Description                                                                                | Required |
| --------------- | ------------------------------------------------------------------------------------------ | -------- |
| `--output`      | Specifies the output file path for the generated DOCX report.                              | Yes      |
| `--template`    | Specifies the input file path for the DOCX report template.                                | Yes      |
| `--data`        | Specifies the input file path for the AttackForge project JSON export.                     | Yes      |
| `--quiet`, `-q` | Suppresses progress output while the report is being generated. Errors are still reported. | No       |

Examples:

```bash
$ reportgen --output=./report.docx --data=./data.json --template=./templates/report_template.docx
$ reportgen --quiet --output=./report.docx --data=./data.json --template=./templates/report_template.docx
```

### ReportGen Node library

Install the library in your project:

```
$ npm install @attackforge/reportgen-node
```

The package ships CommonJS and an ES module side by side, so both `require('@attackforge/reportgen-node')` and `import ... from '@attackforge/reportgen-node'` work.

The library exports one function:

```typescript
generateIndividualReport(docxTemplate: ArrayBuffer, reportData: any, options?: ReportGenOptions): Promise<ArrayBuffer>
```

| Argument                     | Description                                                               |
| ---------------------------- | ------------------------------------------------------------------------- |
| `docxTemplate: ArrayBuffer`  | The DOCX template file to generate the report with.                       |
| `reportData: any`            | The parsed AttackForge JSON report data to compile into the template.     |
| `options?: ReportGenOptions` | Optional. `{ logger?: ReportGenLogger }`. See "Control log output" below. |

It returns a `Promise` that resolves to an `ArrayBuffer` containing the generated DOCX document.

**TypeScript example** (from the package documentation):

```typescript
import { readFile, writeFile } from 'node:fs/promises';
import { generateIndividualReport } from '@attackforge/reportgen-node';

async function readDataFileContents(filePath: string): Promise<any> {
  const dataFileContents = await readFile(filePath, {
    encoding: 'utf-8'
  });

  return JSON.parse(dataFileContents);
}

async function readDocxTemplateFileContents(templateFilePath: string): Promise<ArrayBuffer> {
  return readFile(templateFilePath);
}

async function exampleUsage(): Promise<void> {
  const templateFileContents = await readDocxTemplateFileContents('./template.docx');
  const dataFileContents = await readDataFileContents('./data.json');

  const reportOutput = await generateIndividualReport(templateFileContents, dataFileContents);

  await writeFile('report.docx', Buffer.from(reportOutput));
}
```

**JavaScript example** (from the package documentation):

```javascript
const { readFile, writeFile } = require('node:fs/promises');
const { generateIndividualReport } = require('@attackforge/reportgen-node');

async function readDataFileContents(filePath) {
  const dataFileContents = await readFile(filePath, {
    encoding: 'utf-8'
  });

  return JSON.parse(dataFileContents);
}

async function readDocxTemplateFileContents(templateFilePath) {
  return readFile(templateFilePath);
}

async function exampleUsage() {
  const templateFileContents = await readDocxTemplateFileContents('./template.docx');
  const dataFileContents = await readDataFileContents('./data.json');

  const reportOutput = await generateIndividualReport(templateFileContents, dataFileContents);

  await writeFile('report.docx', Buffer.from(reportOutput));
}
```

**Control log output**

By default, report generation writes progress lines, template warnings and the output of the `$help[...]` template tag to the global `console`. To redirect or silence it, pass a console-shaped `logger` in `options`:

```typescript
type ReportGenLogger = Partial<Pick<Console, 'log' | 'groupCollapsed' | 'groupEnd'>>;

type ReportGenOptions = {
  logger?: ReportGenLogger,
};
```

Any method you leave out falls back to `console`. To silence all output, supply all three methods:

```typescript
const reportOutput = await generateIndividualReport(templateFileContents, dataFileContents, {
  logger: {
    log() {},
    groupCollapsed() {},
    groupEnd() {},
  },
});
```

To forward it to your own logging framework:

```typescript
const reportOutput = await generateIndividualReport(templateFileContents, dataFileContents, {
  logger: {
    log: (...args) => myLogger.info(...args),
    groupCollapsed: (...args) => myLogger.info(...args),
    groupEnd: () => {},
  },
});
```

The `$help[...]` tag emits browser-style `%c` format strings with CSS arguments, intended for the DevTools console. A custom `logger` receives those arguments as they are.

## Step 3: Fetch the report data and template

Use the Self-Service API to get what ReportGen needs. You'll need a Self-Service API key, and access to the project.

| To get                           | Use                                                                                            | Notes                                                                |
| -------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| The project's report data (JSON) | [GetProjectReportData](https://docs.attackforge.com/rest-api/methods/getProjectReportData)     | Save it as a `.json` file, or pass the parsed JSON to the library.   |
| The list of report templates     | [GetReportTemplates](https://docs.attackforge.com/rest-api/methods/getReportTemplates)         | Find the template for the report type you want.                      |
| The template file (DOCX)         | [DownloadReportTemplate](https://docs.attackforge.com/rest-api/methods/downloadReportTemplate) | Save it as a `.docx` file, or keep it in memory as an `ArrayBuffer`. |

You can also keep your own templates in source control, and fetch only the report data each time.

## Step 4: Generate the report

Combine the CLI or library, the template and the report data.

**Example** — a shell script for a CI/CD job or scheduled task.

```bash
#!/usr/bin/env bash
set -euo pipefail

# Example values — replace with your own
AF_HOST="https://yourtenant.attackforge.com"
PROJECT_ID="your-project-id"
TEMPLATE_ID="your-template-id"

# 1. Fetch the project report data (GetProjectReportData)
curl -sSf -H "X-SSAPI-KEY: ${AF_API_KEY}" \
  "${AF_HOST}/<getProjectReportData path for ${PROJECT_ID}>" -o data.json

# 2. Download the report template (DownloadReportTemplate)
curl -sSf -H "X-SSAPI-KEY: ${AF_API_KEY}" \
  "${AF_HOST}/<downloadReportTemplate path for ${TEMPLATE_ID}>" -o template.docx

# 3. Generate the report
npx @attackforge/reportgen-cli --quiet \
  --data=./data.json --template=./template.docx --output=./report.docx

# 4. Upload the report back to the project (Self-Service API upload endpoint)
curl -sSf -H "X-SSAPI-KEY: ${AF_API_KEY}" \
  -F "file=@./report.docx" \
  "${AF_HOST}/<upload endpoint path for ${PROJECT_ID}>"
```

## Trigger reports automatically

You choose when your report automation runs. You can trigger it from outside AttackForge, or from inside AttackForge with [Flows](https://support.attackforge.com/app/automations-and-integrations/flows) and [Actions](https://support.attackforge.com/app/automations-and-integrations/actions).

### Trigger reports with Flows

Flows is AttackForge's workflow automation engine. A Flow starts from a trigger, then runs HTTP Actions and Script Actions written in [AFScript](https://support.attackforge.com/app/automations-and-integrations/afscript).

ReportGen runs in your environment, not in AttackForge, so a Flow doesn't generate the report itself. Instead, it tells your report automation when to run. Use an HTTP Action to call your report service or CI/CD pipeline, and pass it the project ID. Your automation then fetches the data and template, and generates the report as described in steps 3 and 4.

| Flow trigger                        | Use it to generate a report (examples)                                                                                        |
| ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| **Internal Events**                 | When something changes in AttackForge, such as a project being updated.                                                       |
| **Scheduled Events**                | On a schedule, such as a weekly status report for every active project.                                                       |
| **Action Events**                   | When a user clicks an Action. See "Trigger reports with Actions" below.                                                       |
| **External Events (HTTP Triggers)** | When another system calls the Flow, for example to request a report or to run extra steps before calling your report service. |

**Example** — a Flow that asks your report service for a report:

1. **Trigger:** Scheduled Event, every Monday at 8 am.
2. **HTTP Action:** fetch the active projects from the Self-Service API.
3. **Script Action:** for each project, build a request with its project ID and report template.
4. **HTTP Action:** send the request to your report service, which runs the ReportGen CLI or library.

Store your report service's credentials as Flow secrets or User Secrets, not in scripts.

### Trigger reports with Actions

Actions add your own buttons to the AttackForge interface. They need the Flows module. When a user runs an Action, it triggers its linked Action Event Flows.

Add a **Generate report** Action (example) to the Actions menu on Projects, so testers and project managers can request a report without leaving AttackForge:

1. **Create the Flow.** Set its trigger to an Action Event, and add an HTTP Action that sends the project ID to your report service.
2. **Create the Action** on Projects, and link it to the Flow.
3. **Add a form (optional).** Let users choose options, such as the report template or who to send the report to. The answers are available to the Flow in `data.form`.
4. **Share the Action** with the roles, groups or users who should be able to run it.

Users can check the run in the Action Runs Manager, and view the Flow Run Logs if they have permission.

**Close the loop.** Once your report service has generated the report, it can upload it back to the project with the Self-Service API's upload endpoints. The user who clicked the Action then finds the finished report on the project.

### Other triggers

| Trigger                                | How (examples)                                                                                                                                                                                                                         |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **On a schedule, outside AttackForge** | Run the script from cron, a scheduled CI/CD job or a task scheduler.                                                                                                                                                                   |
| **In a pipeline**                      | Add it as a CI/CD step after automated security testing, and attach the report to the build.                                                                                                                                           |
| **From the Events API**                | Connect to the Events channel with a websocket client, and run your automation when a matching event arrives. See [Self-Service Events API](https://support.attackforge.com/app/automations-and-integrations/self-service-events-api). |
| **On request**                         | Wrap it in an internal tool or chat command.                                                                                                                                                                                           |

## Send the report on

Once the DOCX is generated, your automation can send it wherever it's needed, for example:

* **Store it back on the project.** Use the Self-Service API's upload endpoints to attach the report to the project in AttackForge, so everyone with access to the project can find it there.
* Upload it to a document management system or client portal.
* Attach it to a ticket, email or chat message.
* Convert it to PDF with your own tools before sharing.
* Store it with the build or release it relates to.

## Tips

* **Test templates by hand first.** Get a template working in ReportGen before you automate it.
* **Pin the ReportGen version** in your automation, and update it on purpose, so reports don't change unexpectedly.
* **Use `--quiet` in pipelines** to keep logs short. Errors are still reported.
* **Keep API keys out of scripts.** Store them in your CI/CD secrets or a secrets manager, and pass them in as environment variables.
* **Use a dedicated API user** with access to only the projects the automation needs.
* **Silence or capture `$help` output** with the `logger` option, so debugging tags in templates don't flood your logs.
* **Install `canvas` dependencies** on build agents that don't have prebuilt binaries, or charts won't render.

## FAQ

**Where are automated reports generated?** On whatever machine runs the ReportGen CLI or library. They're never generated on AttackForge servers.

**Should I use the CLI or the library?** Use the CLI for scripts, CI/CD jobs and scheduled tasks. Use the library to build report generation into your own Node.js application.

**Which Node.js version do I need?** 24.15.0 or later. Node 26+ is also supported.

**What does ReportGen produce?** A DOCX report.

**Can I use my own templates?** Yes. Download them from AttackForge with the API, or keep your own copies and pass them to ReportGen.

**Can I generate reports for several projects at once?** Yes. Loop over the projects in your script, and call ReportGen once for each. The library's `generateIndividualReport` produces one report per project.

**Why are there no charts in my report?** The library needs `canvas` to render charts. Check that it installed correctly on the machine running ReportGen.

**Do templates behave the same as in the app?** They use the same template language, so the same filters, functions, styles, tables and charts work.

## Related pages

* [Flows](https://support.attackforge.com/app/automations-and-integrations/flows)
* [Actions](https://support.attackforge.com/app/automations-and-integrations/actions)
* [AFScript](https://support.attackforge.com/app/automations-and-integrations/afscript)
* [Self-Service Events API](https://support.attackforge.com/app/automations-and-integrations/self-service-events-api)
* [Reporting overview](https://support.attackforge.com/app/modules/reporting/overview)
* [Template functions](https://support.attackforge.com/app/modules/reporting/template-functions)
* [Template filters](https://support.attackforge.com/app/modules/reporting/template-filters)
* [Template charts](https://support.attackforge.com/app/modules/reporting/template-charts)
* [ReportGen CLI on npm](https://www.npmjs.com/package/@attackforge/reportgen-cli)
* [ReportGen Node library on npm](https://www.npmjs.com/package/@attackforge/reportgen-node)
* [ReportGen on GitHub](https://github.com/AttackForge/ReportGen)
* [Self-Service REST API documentation](https://docs.attackforge.com/rest-api/methods/getProjectReportData)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://support.attackforge.com/app/automations-and-integrations/report-automation.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
