> ## Documentation Index
> Fetch the complete documentation index at: https://docs.oasm.io/llms.txt
> Use this file to discover all available pages before exploring further.

# 开发者指南

> 搭建 OASM 开发环境，从源码运行服务，并管理数据库、代码生成和环境变量

本指南介绍如何从源码开发 OASM：克隆 monorepo、初始化环境、在本地运行 Console、Core API 和 Worker、管理数据库迁移，以及各服务所需的环境变量。生产部署请参阅 [部署](https://docs.oasm.io/zh/deployment.md)。

## 前提条件

开始之前，请确保已安装以下工具：

* **Task (taskfile)**：[安装指南](https://taskfile.dev/#/installation)
* **Node.js v22+**：[安装指南](https://nodejs.org/en/download/package-manager)
* **Go 1.26+**：[安装指南](https://go.dev/doc/install)
* **PostgreSQL v17+**（需 pgvector 扩展）
* **Docker & Docker Compose**（推荐用于数据库和完整技术栈）

## 克隆仓库

```bash theme={null}
git clone https://github.com/oasm-platform/open-asm.git
cd open-asm
```

该仓库是一个 monorepo，使用 **pnpm workspaces** 组织基于 Node 的服务（`console` 和 `core-api`），以及 Go 编写的 `worker`。

## 项目结构

```
open-asm/
├── core-api/           # NestJS API server
│   ├── src/            # Source code
│   ├── example.env     # Environment template
│   └── package.json
├── console/            # React web interface
│   ├── src/            # React components
│   ├── public/         # Static assets
│   └── package.json
├── worker/             # Go-based scanning workers
│   ├── cmd/            # CLI and App entry points
│   ├── internal/       # Business logic
│   ├── scripts/        # Install scripts (install.ps1, install.sh)
│   ├── go.mod          # Go module definition
│   └── .example.env    # Environment template
├── grpc-client/        # Generated gRPC stubs (Go + TypeScript)
├── .open-api/          # Auto-generated API docs
├── docker-compose.yml  # Container orchestration
├── taskfile.yml        # Task automation
└── README.md           # Documentation
```

* **`console/`**：React 19 + TanStack Router + Vite。
* **`core-api/`**：NestJS 11（REST 端口 `6276`，gRPC 端口 `16276`）。
* **`worker/`**：Go 扫描 Worker（CLI 和应用入口）。

## 初始化开发环境

运行以下命令设置本地开发环境：

```bash theme={null}
task init
```

该命令会：

* 为 `core-api`、`console` 和 `worker` 复制示例环境文件（`.env`）
* 使用 `npm` 安装项目依赖（由 task 为每个 workspace 管理）
* 为 Worker 安装 Go 依赖
* 将 Worker 安全工具（nuclei、subfinder、httpx、naabu、dnsx）安装到 `worker/oasm-tools/`

运行 `task init` 后，可以使用 `task dev` 启动所有服务，或按下文所述单独运行。

## 运行服务

### 使用 Task 运行所有服务

同时启动 API 和 Console 开发服务器：

```bash theme={null}
task dev
```

这会启动：

* Core API：`http://localhost:6276`
* Console：`http://localhost:5173`（Vite 开发服务器）

### Core API

```bash theme={null}
task api:dev
```

或直接运行：

```bash theme={null}
cd core-api && npm run start:dev
```

API 运行在端口 `6276`（基础路径 `http://localhost:6276/api`），gRPC 服务器运行在端口 `16276`。

### Console（Web 界面）

```bash theme={null}
task console:dev
```

或直接运行：

```bash theme={null}
cd console && npm run dev
```

### Worker

以 CLI 模式在本地运行 Worker：

```bash theme={null}
task worker:dev
```

使用自定义参数：

```bash theme={null}
task worker:dev replicas=3 maxJobs=10 apiKey=<your-api-key> network=<target-network>
```

以应用模式（由环境变量驱动）运行 Worker：

```bash theme={null}
task worker:dev-app
```

Worker 使用的环境变量请参阅 [Worker](https://docs.oasm.io/zh/worker.md)。

## 数据库设置

`task init` **不会**自动启动 PostgreSQL。你可以：

1. 使用 Docker Compose 启动 PostgreSQL 和 Redis（本地开发两者都需要）：
   ```bash theme={null}
   docker compose up postgres redis -d
   ```
2. 使用你自己的 PostgreSQL 实例，并相应更新 `core-api/.env`。

数据库使用带 pgvector 扩展的 PostgreSQL 17 进行向量运算。如需运行完整技术栈（包括 Worker、geo-ip 和 rustfs），请改为运行 `task docker-compose`，请参阅 [使用 Docker Compose](#using-docker-compose)。

## 数据库迁移

数据库迁移使用 TypeORM 管理。迁移脚本定义在 `core-api/taskfile.yml` 中，可通过 task 命令执行。

### 运行所有待执行的迁移

此命令执行所有待执行的数据库迁移：

```bash theme={null}
task migration:run
```

这会：

* 连接到 PostgreSQL 数据库
* 在 `migrations` 表中检查待执行的迁移
* 运行所有尚未应用的新迁移

### 生成新迁移

使用自定义名称生成新迁移：

```bash theme={null}
task migration:generate MIGRATION_NAME=YourMigrationName
```

例如：

```bash theme={null}
task migration:generate MIGRATION_NAME=AddUserTable
```

这会在 `core-api/src/database/migrations/` 中创建一个新的迁移文件。

### 回滚最近一次迁移

回滚最近执行的迁移：

```bash theme={null}
task migration:revert
```

**注意：** 每次只会回滚一个迁移。如有需要请重复执行。

### 使用 Docker Compose 迁移

如果你更喜欢用 Docker 运行迁移（本地未运行 PostgreSQL 时很有用）：

```bash theme={null}
docker compose up migration
```

这会启动 PostgreSQL 容器（如未运行），运行迁移服务，应用所有待执行的迁移，移除迁移容器，并在迁移完成后启动 `core-api`。如需保留容器用于调试：

```bash theme={null}
docker compose run --rm migration
```

`--rm` 标志确保容器停止后被移除。

## 开发约定

### 代码风格

* **Core API（NestJS）：** 使用 ESLint 和 Prettier。
  ```bash theme={null}
  task api:lint
  ```
* **Console（React）：** 使用 ESLint 和 Prettier。
  ```bash theme={null}
  task console:lint
  ```
* **Worker（Go）：** 使用 `go fmt` 和 `go vet`。
  ```bash theme={null}
  task worker:format
  task worker:lint
  ```

### 测试

* **Core API：** 使用 Jest 进行测试。
  ```bash theme={null}
  task api:test           # Unit tests
  task api:test:one SPEC=path/to/spec.ts   # Run a single test file
  cd core-api && npm run test:watch    # Watch mode
  cd core-api && npm run test:e2e      # End-to-end tests
  ```

* **Console：** 使用 Vitest 进行单元测试，使用 Playwright 进行 e2e 测试。
  ```bash theme={null}
  task console:test       # Unit tests
  cd console && npm run e2e           # E2E tests
  ```

* **Worker：** 使用 Go 测试。
  ```bash theme={null}
  task worker:test
  ```

### 构建

```bash theme={null}
task api:build      # Build the Core API
task build          # Build all services (API + Console + Worker)
```

### API 客户端生成

修改 API 契约后，重新生成 Console API 客户端：

```bash theme={null}
task gen-api
```

它使用 orval 根据 OpenAPI 规范生成 TanStack Query hooks。源规范位于 `core-api` 中的 `.open-api`（文档站点在 `api-reference/openapi.json` 中保存了它的镜像）。

### gRPC 存根生成

修改 proto 文件后，重新生成 gRPC 存根：

```bash theme={null}
task proto
```

这会将 Go 和 TypeScript 存根生成到 `grpc-client/` 中。

## 环境变量

每个服务从各自的 `.env` 文件读取配置，这些文件由 `task init` 从示例模板复制而来。下表列出本地开发中使用的变量及其默认值。

| 服务 | 变量 | 用途 | 默认值 |
| - | - | - | - |
| `core-api` | `POSTGRES_HOST` | PostgreSQL 服务的主机 | — |
| `core-api` | `REDIS_URL` | Redis 连接字符串（包含数据库密码） | `redis://:password@redis:6379/0` |
| `core-api` | `GEO_IP_URL` | 用于资产位置的 Geo IP 服务端点 | `geo-ip:4360` |
| `core-api` | `OASM_CLOUD_APIKEY` | OASM Cloud API 密钥 | — |
| `core-api` | `RUSTFS_ENDPOINT` | 用于截图和产物的对象存储端点 | — |
| `core-api` | `ENCRYPTION_KEYS` | 用于加密已存储凭据的密钥；最后一个用于加密。本地可选（回退到内置密钥）；部署时必填 | 示例值 |
| `core-api` | `BETTER_AUTH_SECRET` | 签名会话和邮箱验证链接。本地可选；部署时必填 | — |
| `core-api` | `BASE_URL` | Console 的公网 URL，用于认证链接和 Telegram Webhook。本地留空 | — |
| `worker` | `WORKER_API_KEY` | Worker 加入时使用的密钥：**连接 Worker** 对话框中的一次性 API 密钥，或全局 Worker 使用核心 API 的 `OASM_CLOUD_APIKEY` | `change_me` |
| `worker` | `WORKER_GRPC_HOST` | Core API 的 gRPC 主机 | `core-api` |
| `worker` | `WORKER_GRPC_PORT` | Core API 的 gRPC 端口 | `16276` |
| `worker` | `WORKER_MAX_CONCURRENCY` | 每个 Worker 的最大并发任务数 | `10` |
| `worker` | `WORKER_TOOL_PATH` | 扫描工具的安装目录 | `/app/oasm-tools` |
| `console` | `VITE_API_URL` | Console 访问 Core API 所用的基础 URL（构建/开发默认值） | `http://localhost:6276` |

> [!CAUTION]
>
> 切勿提交 `.env` 文件，它们已被 gitignore。Worker 的 `WORKER_API_KEY` 必须是有效的一次性 API 密钥，或等于核心 API 的 `OASM_CLOUD_APIKEY`；否则 Worker 无法加入，请参阅 [Worker](https://docs.oasm.io/zh/worker.md)。

## 使用 Docker Compose

使用 Docker Compose 运行整个技术栈：

```bash theme={null}
task docker-compose
```

这会启动：

* Console（端口 3000）
* Core API（端口 6276，gRPC 端口 16276）
* 3 个 Worker 实例
* 带 pgvector 的 PostgreSQL（端口 5432）
* Redis（端口 6379）
* Geo-IP 代理（端口 4360）
* Rustfs S3 存储（端口 9000）

## 本地 CI 测试

推送更改之前，你可以使用 [act](https://github.com/nektos/act) 在本地运行 GitHub Actions 工作流，及早发现问题。

### 前提条件

* 必须安装并运行 Docker Desktop
* 安装 act：
  ```bash theme={null}
  # Linux/macOS
  curl -fsSL https://raw.githubusercontent.com/nektos/act/master/install.sh | bash

  # Windows (Git Bash)
  curl -fsSL https://raw.githubusercontent.com/nektos/act/master/install.sh | bash
  ```

### 用法

```bash theme={null}
# List available workflows
bash .github/scripts/test-local.sh

# Run a specific workflow
bash .github/scripts/test-local.sh check-lint
bash .github/scripts/test-local.sh worker-ci

# Validate all workflows (dry-run)
bash .github/scripts/test-local.sh --all

# Custom act binary path
ACT_BIN=act bash .github/scripts/test-local.sh check-lint
```

### 本地测试对应关系

| CI 工作流 | 本地命令 |
| - | - |
| `check-lint.yml` | `task lint` |
| `check-test.yml` | `task api:test` |
| `check-build.yml` | `task build`（需要 Docker） |
| `frontend-tests.yml` | `cd console && npm run test:run` |
| `worker-ci.yml` | `task worker:lint && task worker:check` |

### 注意事项

* 使用 `docker/build-push-action` 进行多平台构建的工作流（`build-release.yml`、`build-nightly.yml`）需要 QEMU 和原生 CI 运行器，无法在本地运行。
* 在浅克隆中，`dorny/paths-filter` 可能无法正确检测文件变更。请使用 `--full-history` 或测试特定任务。
* Docker 层缓存（`type=gha`）在本地不可用，但构建仍可正常进行。

## 贡献

欢迎贡献！请按以下步骤操作：

1. Fork 本仓库。
2. 创建功能分支：`git checkout -b feature/amazing-feature`。
3. 进行更改，并按照 [Conventional Commits](https://www.conventionalcommits.org/) 提交：
   ```bash theme={null}
   git commit -m 'feat(scope): add amazing feature'
   ```
4. 在本地测试 CI 工作流：`bash .github/scripts/test-local.sh <workflow>`
5. 推送到分支：`git push origin feature/amazing-feature`。
6. 创建 Pull Request。

提交 PR 前，请确保你的代码符合项目的编码规范并通过所有测试。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.