Add AI project map and init workflow for faster repo context

This commit is contained in:
xtcnet 2026-03-19 12:20:58 +07:00
parent 680c9261f6
commit 14c4e1ee5c
2 changed files with 376 additions and 50 deletions

64
.agents/workflows/init.md Normal file
View file

@ -0,0 +1,64 @@
---
description: Initialize agent context for the D3V-Server project
---
## /init Workflow
Use this workflow at the start of a new session.
Goal: understand the repo quickly without scanning the full codebase.
### Required first step
1. Read `D:\AntiGravity\D3V-Server\AI_CONTEXT.md`
Do not start with a broad recursive scan unless the user explicitly asks for a repo-wide audit.
### Minimal orientation sequence
After reading `AI_CONTEXT.md`, open only these files:
1. `D:\AntiGravity\D3V-Server\README.md`
2. `D:\AntiGravity\D3V-Server\backend\index.js`
3. `D:\AntiGravity\D3V-Server\backend\app.js`
4. `D:\AntiGravity\D3V-Server\backend\routes\main.js`
5. `D:\AntiGravity\D3V-Server\frontend\src\main.tsx`
6. `D:\AntiGravity\D3V-Server\frontend\src\App.tsx`
7. `D:\AntiGravity\D3V-Server\frontend\src\Router.tsx`
8. `D:\AntiGravity\D3V-Server\docker\Dockerfile`
That set is normally enough to understand:
- top-level architecture
- backend startup flow
- frontend startup flow
- route structure
- production packaging model
### Area-specific follow-up
Only then open files for the requested area:
- Backend/API task: inspect `backend/routes/`, `backend/internal/`, `backend/models/`
- Frontend/UI task: inspect `frontend/src/pages/`, `frontend/src/hooks/`, `frontend/src/api/`
- WireGuard task: inspect `backend/internal/wireguard.js`, `backend/routes/wireguard.js`, `backend/routes/wg_public.js`, `frontend/src/pages/WireGuard/`
- Build/deploy task: inspect `docker/`, `scripts/`, `install.sh`
- Docs task: inspect `docs/`
- Test task: inspect `test/`
### Important reminders
- This is a multi-package repo. Commands run in subdirectories, not from one obvious root workspace.
- Docker packaging is part of the product behavior, not just deployment.
- The frontend must be built before the production Docker image can be built.
- Some runtime behavior depends on env vars, mounted volumes, and container capabilities.
- Avoid rewriting upstream-shaped structure unless the task requires it.
### Ready message
When initialization is complete, summarize the project in 3-5 lines:
- what the app is
- backend entry
- frontend entry
- production assembly path
- the specific area relevant to the user's task

View file

@ -1,66 +1,328 @@
# AI Context for NPM-WG Project
# AI Context for D3V-Server
## 1. Project Overview
**NPM-WG** is a custom fork of [xGat3](https://github.com/NginxProxyManager/nginx-proxy-manager) integrated with **WireGuard VPN** management capabilities, inspired by `wg-easy`.
This file is the fast-start map for AI agents working in this repository.
Read this first. Do not scan the entire repo unless the task actually requires it.
The project structure remains mostly identical to xGat3, but specific backend and frontend modules have been added to manage WireGuard securely inside the Docker container without needing external dependencies.
## 1. What this project is
---
`D3V-Server` is a custom fork of Nginx Proxy Manager / xGat3 with an added
WireGuard management module and some project-specific admin features.
## 2. Technology Stack
- **Backend**: Node.js, Express.js, Knex (Query Builder), SQLite/MySQL/PostgreSQL. Uses ES Modules (`"type": "module"`).
- **Frontend**: React 18, TypeScript, Vite, React Router, React Bootstrap (`ez-modal-react`), Formik, React Query (`@tanstack/react-query`).
- **Container**: Alpine Linux with `s6-overlay` for service process management.
Canonical repository:
---
- `https://src.d3v.ac/xtcnet/D3V-Server`
## 3. WireGuard Integration Architecture
Treat that repository as the source of truth for this project.
If another upstream is mentioned, assume it is a historical ancestor or reference,
not the primary project remote, unless the task says otherwise.
### Core Idea
WireGuard functionality is disabled by default and enabled via the `WG_ENABLED` environment variable. The system uses a Node.js cron wrapper to manipulate the WireGuard `wg` and `wg-quick` CLI tools directly. It leverages Docker volume mapping (`/etc/wireguard`) to maintain state.
At a high level:
### Backend Map (Node.js)
If you need to edit WireGuard logic, check these files:
- **`backend/lib/wg-helpers.js`**: Shell wrappers for `wg` CLI (create keys, parse CIDR, parse `wg show` dumps, gen configurations).
- **`backend/lib/crypto.js`**: AES-256-GCM encrypt/decrypt helper for sensitive DB fields. Uses `DB_ENCRYPTION_KEY` env var. Transparent passthrough if key is not set (backward compat).
- **`backend/internal/wireguard.js`**: Core business logic. Manages interface start/stop, adding/removing clients, IP allocation, and token expiration checking via cron.
- **`backend/routes/wireguard.js`**: REST APIs exposing CRUD operations to the frontend. Note: Handlers use ES module export functions syntax.
- **`backend/routes/main.js`**: Mounts the `/api/wireguard` routes.
- **`backend/index.js`**: Contains the startup hook `internalWireguard.startup(knex)` and graceful SIGTERM shutdown hooks.
- **`backend/migrations/20260307000000_wireguard.js`**: Knex schema initialization for tables `wg_interface` and `wg_client`. *Note: Must use ES Module `export function up()` instead of `exports.up`!*
- `backend/` is the API server and system orchestration layer.
- `frontend/` is the admin web UI.
- `docker/` is the production runtime assembly.
- `test/` contains Cypress and API-spec checks.
- `docs/` is a separate VitePress docs site.
### Frontend Map (React)
If you need to edit the UI/UX, check these files:
- **`frontend/src/api/backend/wireguard.ts`**: API fetch helper definitions.
- **`frontend/src/hooks/useWireGuard.ts`**: `@tanstack/react-query` data fetchers and mutators.
- **`frontend/src/pages/WireGuard/index.tsx`**: Main UI Page rendering the interface stats and clients table.
- **`frontend/src/modals/WireGuardClientModal.tsx`**: Form to create a new client. *Note: Modal built explicitly over `react-bootstrap/Modal` to prevent backdrop freezing issues.*
- **`frontend/src/modals/WireGuardQRModal.tsx`**: Generates and parses QR codes.
- **`frontend/src/Router.tsx` & `SiteMenu.tsx`**: Routing and UI Navigation injection points for WireGuard UI.
The production app is not "just backend" or "just frontend":
Docker assembles the backend and the prebuilt frontend into one image.
---
## 2. Repo map
## 4. Build & Deployment Gotchas
```text
D3V-Server/
|- backend/ Node.js + Express API, DB, WireGuard logic
| |- routes/ REST endpoints
| |- internal/ background/system services
| |- models/ Objection models
| |- migrations/ Knex migrations
| |- schema/ API schema compilation
| |- templates/ config/template generation
| |- app.js Express app wiring
| `- index.js backend startup entry
|- frontend/ React + TypeScript + Vite SPA
| |- src/
| | |- pages/ top-level screens
| | |- components/ shared UI
| | |- hooks/ data and UI hooks
| | |- api/ backend API wrappers
| | |- modals/ modal flows
| | |- context/ auth/theme/locale providers
| | |- Router.tsx route table
| | `- main.tsx frontend entry
| `- vite.config.ts dev/build config
|- docker/ production image and runtime scripts
|- docs/ VitePress docs site
|- test/ Cypress E2E and swagger lint
|- scripts/ helper scripts
|- install.sh install/update/reset automation for deployment
`- README.md user-facing overview
```
### Line Endings (CRLF vs LF)
- **CRITICAL**: All files in `docker/rootfs` and `docker/scripts` are used by `s6-overlay` inside Alpine Linux. **They MUST be formatted using UNIX Line Endings (LF)**. If you download this repository on Windows, ensure the git config does not automatically convert text files to `CRLF`, otherwise container booting will crash with `s6-rc-compile: fatal: invalid type: must be oneshot, longrun, or bundle`.
## 3. Runtime architecture
### Compilation Steps
- The React Frontend **MUST** be pre-built before Docker can build.
- You must run `yarn install`, `yarn locale-compile`, and `yarn build` inside the `frontend/` directory before `docker build`.
- Use the script `./scripts/build-project.sh` to execute the full pipeline if you have a bash environment.
```mermaid
flowchart LR
A["Browser"] --> B["Frontend SPA<br/>frontend/src/main.tsx"]
B --> C["React Router + pages<br/>frontend/src/Router.tsx"]
C --> D["Backend API<br/>backend/app.js"]
D --> E["Route handlers<br/>backend/routes/*"]
E --> F["Models / DB<br/>Knex + Objection"]
D --> G["Internal services<br/>backend/internal/*"]
G --> H["WireGuard CLI / system state"]
I["docker/Dockerfile"] --> D
I --> B
```
### Docker Config Requirements
- **Required capabilities**: `--cap-add=NET_ADMIN` and `--cap-add=SYS_MODULE` are required for WireGuard to manipulate interfaces.
- **Sysctls**: `--sysctl net.ipv4.ip_forward=1` must be applied to the container.
- **Volumes**: Volume `/etc/letsencrypt` is severely required by original NPM core.
- **DB Encryption**: `DB_ENCRYPTION_KEY` must be a 64-char hex string (`openssl rand -hex 32`). It is auto-generated by `install.sh` and saved to `/opt/d3v-npmwg/.env`. **Losing this key means WireGuard private keys in the database cannot be decrypted.**
## 4. First files to open for orientation
---
If a new session needs project understanding, open these files in order:
## 5. Agent Instructions
If you are an AI reading this file:
1. Treat existing NPM-specific code as sacred. Do not modify global `.ts` hooks or Knex config unless instructed.
2. If fixing a bug in the Frontend, use `useWgClients()` / `useInterfaceStatus()` standard hooks. Use React-Bootstrap `Modal` instead of raw div class names.
3. If changing the DB, create a new `backend/migrations/*.js` file in ES Module format.
4. When testing out scripts, remember that the docker container requires port mapping to 51820/udp.
1. `AI_CONTEXT.md`
2. `README.md`
3. `backend/index.js`
4. `backend/app.js`
5. `backend/routes/main.js`
6. `frontend/src/main.tsx`
7. `frontend/src/App.tsx`
8. `frontend/src/Router.tsx`
9. `docker/Dockerfile`
10. the relevant package manifest for the area being changed
That is usually enough to understand the system without scanning everything.
## 5. How the backend starts
Main entry: `backend/index.js`
Startup flow:
1. Run DB migrations via `migrateUp()`
2. Run setup/bootstrap via `setup()`
3. Compile/load schema via `getCompiledSchema()`
4. Optionally fetch IP ranges
5. Start timers for internal certificate/IP-range jobs
6. If `WG_ENABLED != false`, start WireGuard service hooks
7. Start Express server on port `3000`
Important implication:
- Many issues that look like "API bugs" can actually come from startup/setup/migration state.
- WireGuard startup failure is logged, but the backend may continue without WireGuard functionality.
## 6. How the backend is organized
Core files:
- `backend/index.js`: process startup and shutdown
- `backend/app.js`: Express middleware, helmet, rate limit, auth, route mounting
- `backend/routes/main.js`: root API router
- `backend/db.js`: DB handle creation
- `backend/lib/config.js`: database/config/env resolution
- `backend/setup.js`: instance bootstrap/setup flow
Important route groups from `backend/routes/main.js`:
- `/api/schema`
- `/api/tokens`
- `/api/users`
- `/api/audit-log`
- `/api/reports`
- `/api/settings`
- `/api/version`
- `/api/nginx/proxy-hosts`
- `/api/nginx/redirection-hosts`
- `/api/nginx/dead-hosts`
- `/api/nginx/streams`
- `/api/nginx/access-lists`
- `/api/nginx/certificates`
- `/api/wireguard`
- `/api/database`
Public WireGuard portal:
- `backend/app.js` mounts `wg_public` before JWT middleware at `/wg-public`
- frontend has a dedicated route branch for `/wg-public`
## 7. How the frontend is organized
Entry path:
- `frontend/src/main.tsx` -> `frontend/src/App.tsx` -> `frontend/src/Router.tsx`
Frontend routing model:
- `Router.tsx` checks health/setup/auth before rendering the main app
- `/wg-public/*` bypasses the standard authenticated admin shell
- most admin pages are lazy-loaded from `frontend/src/pages/*`
Useful places by task:
- New screen or route: `frontend/src/Router.tsx` and `frontend/src/pages/`
- Backend API bindings: `frontend/src/api/`
- Server state/query logic: `frontend/src/hooks/`
- Shared app state: `frontend/src/context/`
- Reusable UI: `frontend/src/components/`
- Modal workflows: `frontend/src/modals/`
## 8. Build, test, lint commands
This repo is multi-package. There is no obvious root workspace command.
Run commands in the relevant subdirectory.
### Backend
Working directory: `backend/`
- `yarn lint`
- `yarn prettier`
- `yarn validate-schema`
- `yarn regenerate-config`
- likely local start: `node index.js`
### Frontend
Working directory: `frontend/`
- `yarn dev`
- `yarn build`
- `yarn lint`
- `yarn preview`
- `yarn test`
- `yarn locale-extract`
- `yarn locale-compile`
- `yarn locale-sort`
### Docs
Working directory: `docs/`
- `yarn dev`
- `yarn build`
- `yarn preview`
### Test
Working directory: `test/`
- `yarn cypress`
- `yarn cypress:headless`
- `yarn cypress:dev`
- `yarn swagger-lint`
### Full build
The production Docker build expects the frontend to be built first.
Common flow:
1. build frontend in `frontend/`
2. build image with `docker/Dockerfile`
Helper script:
- `scripts/build-project.sh`
## 9. Key technologies
- Backend: Node.js, Express 5, Knex, Objection, AJV
- Databases: SQLite by default, MySQL/Postgres supported
- Frontend: React, TypeScript, Vite, React Router, TanStack Query, Tabler UI
- Testing: Vitest for frontend, Cypress for E2E
- Packaging/runtime: Docker, nginx, s6 overlay
- System integration: WireGuard CLI tools inside the container/runtime
## 10. Configuration model
The backend resolves configuration in this order:
1. JSON config file from `NODE_CONFIG_DIR` / `config/*.json`
2. environment variables
3. SQLite fallback using `/data/database.sqlite`
Important file:
- `backend/lib/config.js`
Notes:
- JWT keys are persisted to `/data/keys.json`
- default DB fallback is SQLite
- production behavior often depends on mounted volumes and env vars, not just source code
## 11. WireGuard-specific map
When the task is specifically about WireGuard, start here:
- `backend/internal/wireguard.js`
- `backend/routes/wireguard.js`
- `backend/routes/wg_public.js`
- `frontend/src/pages/WireGuard/`
- `frontend/src/api/backend/wireguard.ts`
- `frontend/src/hooks/useWireGuard.ts`
- relevant migration files in `backend/migrations/`
Operational assumptions:
- `WG_ENABLED` controls whether WireGuard startup hooks run
- runtime requires container/network capabilities such as `NET_ADMIN`
- some behavior only makes sense inside the Dockerized runtime
## 12. Production packaging model
Production image definition:
- `docker/Dockerfile`
Important facts:
- it copies `backend/` into `/app`
- it copies `frontend/dist` into `/app/frontend`
- it installs runtime dependencies inside the image
- it relies on s6-overlay and rootfs scripts
This means:
- frontend must be built before image build
- Docker/runtime files are part of app behavior, not just deployment plumbing
## 13. Known gotchas
- `docker/Dockerfile` assumes `frontend/dist` already exists
- several scripts are shell-oriented and may be awkward on native Windows
- docs and names are inherited from upstream in places, so naming is mixed:
`nginx-proxy-manager`, `xGat3`, `D3V-Server`, `D3V-NPMWG`
- `README.md` currently has encoding artifacts; do not assume every displayed character is trustworthy
- backend package has no clear `start` script, so use `backend/index.js` as the canonical runtime entry
- do not treat this as a simple SPA-only repo or API-only repo; the Docker assembly matters
## 14. Change strategy for AI agents
When handling a task:
1. Read this file
2. Open only the subsystem entry files for the relevant area
3. Avoid broad repo scans unless the task is cross-cutting
4. Verify whether the change affects Docker/runtime assumptions
5. If the task touches WireGuard, include container/runtime implications in reasoning
Open only what you need:
- backend bug: `backend/index.js`, `backend/app.js`, matching route/service/model files
- frontend bug: `frontend/src/main.tsx`, `App.tsx`, `Router.tsx`, matching page/hook/api files
- build/deploy bug: `docker/Dockerfile`, `scripts/build-project.sh`, `install.sh`
- auth/setup issue: `backend/setup.js`, `backend/routes/tokens.js`, `frontend/src/context/`
## 15. Fast summary
If you only remember one thing:
`D3V-Server` is a Docker-assembled full-stack app where:
- backend runs the API and system logic
- frontend is a Vite React admin UI
- WireGuard is an integrated subsystem, not a separate service
- Docker/runtime files are part of the product behavior
- `backend/index.js`, `backend/app.js`, `backend/routes/main.js`,
`frontend/src/main.tsx`, `frontend/src/App.tsx`,
`frontend/src/Router.tsx`, and `docker/Dockerfile` are the core orientation files