Compare commits

...
3 Commits
Author SHA1 Message Date
ji ruo 96a01bfeba chore(release): prepare v0.3.34 release notes 2026-12-04 15:43:21 +08:00
ji ruo efeb150f26 feat(sandbox-ui): show host sandbox upgrade command in local mode
- Display copyable host upgrade command (`git pull` / `./update.sh --upgrade --tag <version>`) on /system/sandbox and settings SandboxCard when running in local mode.
- Hide the upgrade prompt automatically when Docker sandbox mode is enabled.
2026-12-04 15:43:21 +08:00
ji ruo c49aa703c2 docs(readme): add English README and Open Source Guardian Program notice
- Add README_EN.md with full English translation and language switcher links (defaulting to Chinese README.md).
- Add ChainReactors Open Source Guardian Program notice and link above the screenshots section in both languages.
2026-12-04 15:43:21 +08:00
5 changed files with 918 additions and 6 deletions

No files matched your search

+7
View File
@@ -4,6 +4,13 @@
## [Unreleased] ## [Unreleased]
## [0.3.34] - 2026-12-04
### 新增与改进
- 沙箱容器页与设置页沙箱卡片在本地模式下新增宿主机升级指引:展示 `git pull` 与 `./update.sh --upgrade --tag <version>` 一键复制命令,说明网页更新仅替换容器内主控程序,切换到 Docker 沙箱模式后自动隐藏该提示卡片。
- 仓库主页新增英文版 [README_EN.md](README_EN.md)(默认保持中文 `README.md` 并支持顶部互相切换),并在截图预览前补充链式反应「开源守护计划」说明与申请链接。
## [0.3.33] - 2026-12-04 ## [0.3.33] - 2026-12-04
### 新增与改进 ### 新增与改进
+5
View File
@@ -4,6 +4,8 @@
AI 自主渗透测试系统(Go 后端 + Next.js 前端) AI 自主渗透测试系统(Go 后端 + Next.js 前端)
**简体中文** | [English](README_EN.md)
<p> <p>
<a href="https://www.chainreactors.ai" target="_blank" rel="noopener noreferrer"> <a href="https://www.chainreactors.ai" target="_blank" rel="noopener noreferrer">
<img src="screenshots/chainreactors.png" alt="ChainReactors" height="45" /> <img src="screenshots/chainreactors.png" alt="ChainReactors" height="45" />
@@ -14,6 +16,9 @@ AI 自主渗透测试系统(Go 后端 + Next.js 前端)
--- ---
> **链式反应「开源守护计划」**:免费为开源基础设施项目提供价值 3 万元/月的 CYBER AI 安全检测额度(赠送 3 个月),并由专业团队协助修复,零门槛服务开源社区。
> 链接:[chainreactors.ai/guardian](https://www.chainreactors.ai/guardian/)
## 截图预览 ## 截图预览
> 完整交互见[在线 Demo](https://artex-demo-ruoji6.vercel.app/)。 > 完整交互见[在线 Demo](https://artex-demo-ruoji6.vercel.app/)。
+761
View File
@@ -0,0 +1,761 @@
<div align="center">
# ARTEX
AI Autonomous Penetration Testing System (Go Backend + Next.js Frontend)
[简体中文](README.md) | **English**
<p>
<a href="https://www.chainreactors.ai" target="_blank" rel="noopener noreferrer">
<img src="screenshots/chainreactors.png" alt="ChainReactors" height="45" />
</a>
</p>
</div>
---
> **ChainReactors Open Source Guardian Program**: Free CYBER AI security testing credits worth ¥30,000/month (3 months complimentary) for open-source infrastructure projects, with hands-on remediation assistance from our security team — zero-barrier support for the open-source community.
> Link: [chainreactors.ai/guardian](https://www.chainreactors.ai/guardian/)
## Screenshots
> Try the full interactive UI in the [Live Demo](https://artex-demo-ruoji6.vercel.app/).
| Dashboard (Overview / Token Usage / Activity Stream) | Task List |
| :---: | :---: |
| ![Dashboard](screenshots/dashboard.png) | ![Tasks](screenshots/tasks.png) |
| Task Execution (Sessions / Tool Calls) | Exploration Graph |
| :---: | :---: |
| ![Execution](screenshots/sessions.png) | ![Exploration Graph](screenshots/graph.png) |
| Findings | Assets |
| :---: | :---: |
| ![Findings](screenshots/findings.png) | ![Assets](screenshots/assets.png) |
| Asset Coverage Graph (Force-Directed · Tested Highlight · Collapse/Expand) |
| :---: |
| ![Asset Coverage Graph](screenshots/assets_test.png) |
| Traffic Recording | Human-in-the-Loop Chat |
| :---: | :---: |
| ![Traffic](screenshots/traffic.png) | ![Chat](screenshots/chat.png) |
| Agent Management | LLM Configuration |
| :---: | :---: |
| ![Agents](screenshots/agents.png) | ![LLM](screenshots/llm.png) |
| Intercept Approvals | Backend Logs |
| :---: | :---: |
| ![Intercept](screenshots/intercept.png) | ![Logs](screenshots/logs.png) |
---
## Approval Record Details
Global **Approval Records**, per-task **Intercept Approvals**, and inline approval cards in chat all support expanding full call details. The layout draws inspiration from [AegisHook's CallDetail component](https://github.com/RuoJi6/AegisHook/blob/main/web/src/components/CallDetail.vue) while adopting ARTEX's native UI components and theme.
## Asset Sync (ScopeSentry)
Import asset inventories directly from [ScopeSentry](https://github.com/Autumn-27/ScopeSentry) to avoid duplicate reconnaissance:
- Enter your ScopeSentry URL and API Key on the **Asset Sync** page to connect the data source;
- Select targets and asset types (domains / subdomains / IPs / ports / sites / endpoints…) by **project** or **task**;
- Import in one click and merge into company asset scopes, feeding directly into ARTEX's Asset Graph for agents to explore.
---
## Deploying Your Own Online Demo (Auto-Updated on Releases)
The demo runs only the `web/` frontend built with `NEXT_PUBLIC_MOCK=1`—no Go, PostgreSQL, or LLM keys required. The interface uses mock data and performs no real scanning.
Release pipeline: official release packages, `SHA256SUMS`, and Docker images succeed → the `demo` job in `release.yml` calls `demo.yml` → checks out the tagged commit → builds the mock frontend → deploys to a fixed Vercel production domain. Ordinary `main` pushes, tag-only pushes, failed releases, drafts, and pre-releases do not update the demo. Maintainers still need to keep demo fixtures in `web/src/lib/mock/` up to date for new features.
### Initial Vercel Setup
1. Create an empty project in your Vercel account (e.g. `artex-demo-ruoji6`). Leave **Git disconnected** to avoid deploying on every commit; `web/vercel.json` also disables automatic Git deployments.
2. Under **Settings → Build and Deployment**, select **Next.js** and Node.js **22.x**, set Install Command to `npm ci`, Build Command to `npm run build`, and leave Output Directory at default. **Leave Root Directory empty**: the workflow invokes Vercel CLI from the checked-out `web/` directory and must not nest `web` twice.
3. Under **Environment Variables**, add `NEXT_PUBLIC_MOCK=1` for at least **Production**. Do not set `NEXT_EXPORT=1`, and do not configure database credentials or LLM keys.
4. Copy **Project ID** from **Settings → General**, and **Team ID** from team **Settings → General** (used as `VERCEL_ORG_ID`). Verify your production domain under **Domains**.
5. Create a deployment token in Vercel **Account Settings → Tokens** scoped to the project's team with an appropriate expiry, and store it in GitHub **Settings → Secrets and variables → Actions → Secrets** as `VERCEL_TOKEN`. Never commit tokens to the repository, README, or chat.
Add the following GitHub Actions **Variables** on the same settings page:
| Variable | Value |
| --- | --- |
| `VERCEL_ORG_ID` | Vercel Team ID |
| `VERCEL_PROJECT_ID` | Vercel Project ID |
| `DEMO_URL` | Fixed public production URL with `https://`, e.g. `https://artex-demo-ruoji6.vercel.app` |
### First Deployment & Retries
After merging the configuration into the default branch, open **Actions → deploy-demo → Run workflow**, choose branch `main`, and leave `tag` empty or enter the latest official release tag (e.g. `v0.3.21`). The workflow only accepts published stable releases containing all five platform archives and `SHA256SUMS`, and can also deploy historical releases created before this workflow existed—no need to recreate releases or move tags.
The workflow configures the dedicated demo project with framework Next.js, Node 22.x, empty root directory, `npm ci`, `npm run build`, `NEXT_PUBLIC_MOCK=1` in Production, and binds `DEMO_URL`. Use a dedicated Vercel project, as subsequent deployments maintain these settings.
After deployment succeeds, visit your production domain and verify `tag`, `commit`, and `mock: true` at `/demo-version.json`. Once confirmed, update the demo links in the README header and screenshots section to your production URL.
Subsequent stable releases will update the demo automatically. If a demo deployment fails, the published release archives and Docker images remain valid and the previous demo continues serving traffic; fix configuration and re-run `deploy-demo` without re-releasing. Concurrent releases serialize deployments and re-verify `latest` before building and going live so older builds cannot overwrite newer ones.
The release workflow directly calls `demo.yml` because releases created with `GITHUB_TOKEN` do not trigger downstream `release: published` workflows. `demo.yml` also listens to manually published releases via the GitHub UI with the same stability, completeness, and `latest` checks.
---
## Installation
> Requires **PostgreSQL**; autonomous exploration requires an **LLM** (`ANTHROPIC_API_KEY` or `OPENAI_API_KEY`, configurable via environment variables or the UI).
### Option 1: One-Click Install Script (Recommended)
```bash
git clone https://github.com/RuoJi6/ARTEX.git
cd ARTEX
./install.sh
```
The script supports Docker deployment and local compilation:
- **① Docker Deployment (Recommended)**: Uses `docker-compose.yml` (`postgres` + `docker-socket-proxy` + `artex` + `artex-gateway` TUN/netstack transparent gateway + dynamically spawned non-root `artex-sandbox` containers). Automatically populates `ARTEX_HOST_DATA_DIR`, `ARTEX_GATEWAY_TOKEN`, and a random `POSTGRES_PASSWORD`.
- **② Local Build**: Choose database (existing PostgreSQL or spin one up with Docker) → generate `config.json` → compile single binary with embedded frontend → start.
Non-interactive installation is also supported:
```bash
./install.sh --docker --yes
```
Once started, open **http://localhost:8787** (first visit redirects to `/setup` to set the administrator password).
### Option 2: Docker Compose (Manual)
```bash
git clone https://github.com/RuoJi6/ARTEX.git
cd ARTEX
cp .env.example .env # Set POSTGRES_PASSWORD, ARTEX_HOST_DATA_DIR, ARTEX_GATEWAY_TOKEN
docker compose up -d # Starts postgres + docker-socket-proxy + artex + artex-gateway
# → http://localhost:8787
```
All images support `linux/amd64` and `linux/arm64`: `ruoji6/artex:<tag>` + `ruoji6/artex-gateway:<tag>` + `ruoji6/artex-sandbox:<tag>` (default `latest`).
#### Memory & Process Protection
- **Compose Container**: `artex` defaults to **4 GiB memory, 512 processes/threads**, with container swap disabled; PostgreSQL is not constrained by these limits. Override via `ARTEX_MEMORY_LIMIT` and `ARTEX_PIDS_LIMIT` in `.env`. On low-memory VPS instances, lower the limit to leave headroom for the host, database, and other services. Recreate the container with `docker compose up -d artex` after editing Compose or `.env` (in-place binary updates do not change container limits).
- **Per-Command Tool Limits**: Foreground/background Bash, custom commands, and Python scripts default to **2048 MiB** memory and **120s** timeout. Explicit `timeout_ms` is capped at 600s (or the operator's higher default). Adjust via `ARTEX_TOOL_MEMORY_LIMIT_MB` and `ARTEX_TOOL_TIMEOUT_S`; setting memory limit to `0` disables per-command memory protection. Timed-out foreground commands are terminated rather than auto-backgrounded. Memory limit breaches return explicit errors; check explicit background tasks via `TaskOutput`.
- **Enforcement**: Delegated Linux cgroup v2 enforces kernel memory limits and (when the PID controller is enabled) `ARTEX_TOOL_PIDS_LIMIT` (default 256, `0` disables). By default sub-cgroups are created under the service's own cgroup; local deployments can specify an admin-delegated parent via `ARTEX_TOOL_CGROUP_PARENT`. Inside standard unprivileged Docker containers where cgroups are read-only, Linux falls back to process-tree RSS + swap sampling and macOS uses RSS sampling. Sampling is not a hard cap, so brief spikes may only be caught by the container limit; Windows does not support per-command memory sampling. SDK `Monitor` and interactive PTYs bypass per-command limits but remain bound by container limits in Compose.
- **Inspecting Limits**: Startup logs and authenticated `GET /api/system/metrics` (`limits` field) report effective limits and enforcement mode; on Linux with readable container cgroups, memory and PID caps are reported as well.
Remote MCP servers can use `http` (Streamable HTTP) or `sse` (legacy SSE) in System Settings. Legacy SSE endpoints typically establish an event stream via `GET /sse` and accept JSON-RPC requests at the returned `/message?sessionId=...` path; enter the `/sse` URL and set headers such as `Authorization=Bearer <token>`.
### Option 3: Prebuilt Binaries (Releases)
Download the archive for your platform from [Releases](https://github.com/RuoJi6/ARTEX/releases). Extracting gives `artex` + `start.sh` (`start.bat` on Windows) + `skills/` + `config.example.json`. Choose `linux-arm64` for Linux ARM64 (including ARM64 Kali) or `linux-amd64` for x86_64:
```bash
cp config.example.json config.json # Configure database connection
./start.sh # → http://localhost:8787
```
> Start ARTEX via `start.sh` / `start.bat` rather than running `./artex` directly. The supervisor script inspects the exit code to restart the process and is **required for [one-click in-app updates](#option-1-one-click-in-app-update-recommended)**. Running `./artex` directly will not auto-restart after staging an update.
> Background daemon: `nohup ./start.sh >artex.log 2>&1 &`.
### Option 4: Build Single Binary from Source
```bash
# 1) Export static frontend
cd web && npm ci && npm run build:static && cd ..
# 2) Create embed directory
mkdir -p server/webui/dist
# 3) Copy exported frontend assets
cp -r web/out/. server/webui/dist
# 4) Build binary (-tags embedui embeds the frontend)
CGO_ENABLED=0 go build -tags embedui -o artex ./cmd/artex
./start.sh
```
### Option 5: Build Cross-Platform Release Archives
`build.sh` builds and embeds the frontend, strips debug symbols via Go linker flags, and packages release zip archives. Release mode defaults to Linux amd64/arm64, macOS amd64/arm64, and Windows amd64:
```bash
./build.sh --release
# Output: dist/artex-0.3.3-*.zip
```
UPX self-extracting binaries can fail under some Linux kernels, virtualization layers, or security policies and are therefore disabled by default. Customize targets with `ARTEX_TARGETS`, or pass `--upx` explicitly if your target environment supports it:
```bash
ARTEX_TARGETS=linux/amd64,windows/amd64 ./build.sh --release
./build.sh --target linux/amd64 --upx
```
---
## One-Click Backup & Migration
Under **System Settings → System & Account → Backup & Migration**:
- **Download Backup**: Produces a single `artex-backup-<timestamp>.tar.zst` downloaded directly by the browser. Pause or wait for running/queued tasks to finish before exporting to avoid inconsistent file writes. Includes all PostgreSQL business tables (chunked streaming export within a single snapshot transaction), data directory (task workspaces, sessions, evidence, task archives, MITM CA certificate, traffic blobs, and SQLite index snapshots), and `skills/`. Excludes `server_logs` and `jwt.key`.
- **Restore from Backup**: Install and start ARTEX normally on the target machine, sign in, and upload the backup archive. The server unpacks and validates compatibility against the current schema before restarting. On restart—before any subsystem opens data files—the database is replaced inside a single transaction (failures preserve existing data and move the archive to `data/.restore-failed` for inspection) and data directories are replaced item by item; if file replacement fails, the process exits non-zero so the supervisor retries until complete. The card displays the outcome of the last restore.
- Restoring **overwrites all data on the current instance** and stops running tasks; unfinished tasks from the backup remain paused after restore and must be resumed manually so the new host never fires unexpected requests at targets. Login passwords, Basic Auth, LLM configs, and settings migrate with the database—sign in with the original instance's password afterwards.
- Existing same-named skills on the destination host keep their local versions (preventing older backups from overwriting newer built-in skills); all other skills are restored from the backup.
- Restores are allowed only onto the **same or newer** ARTEX version; backups containing unknown tables or columns are rejected. Absolute paths (such as task archive paths) are automatically rewritten to the new data directory.
- Relies on `start.sh` / `start.bat` (or Docker `ENTRYPOINT`) for restart, same as in-app updates.
- Reserve extra temporary disk space roughly equal to one **uncompressed backup** on the data directory's filesystem during restore. Behind Nginx, widen `client_max_body_size` and disable `proxy_request_buffering` for `/api/system/backup/` as shown in the reverse proxy example below.
## Upgrading
> Upgrades replace only the program while preserving data: Postgres volume `pgdata`, `./data` (`jwt.key` / SQLite, etc.), and `./skills` stay intact. **No manual database migrations are needed**—`artex` idempotently runs `schema.sql` (`ADD COLUMN` / `CREATE INDEX IF NOT EXISTS`) on every startup. Backing up `./data` and PostgreSQL before upgrading is still recommended.
### Option 1: One-Click In-App Update (Recommended)
Open **System Settings** (`/system/settings`) and use the **Version and Updates** card to check and install updates without logging into the server.
Builds from this repository check the latest stable GitHub Release on `RuoJi6/ARTEX`, skipping drafts and pre-releases. Legacy upstream builds point to the original repository, so the first switch requires manually installing a build from this repository; subsequent higher semver releases can be upgraded directly in the UI. Pushing to `main` or pushing a tag without publishing a GitHub Release does not produce an installable update.
Clicking **Update** downloads the platform package → verifies `SHA256SUMS` → smoke-tests the new binary with `-h` → stages `artex.new` → exits so `start.sh` / `start.bat` restarts and swaps the binary. The UI automatically waits for the new version and refreshes.
- **Safe on Failure**: Checksum or smoke-test failures discard the staged file and keep running the current version. If the new binary crashes 3 times in a row on startup, it automatically rolls back to `artex.old` (preserving the failing binary as `artex.failed`).
- **Rollback**: The previous binary is kept as `artex.old` with a rollback button in the UI. Note that database schema changes are not rolled back.
- **Interrupts Running Tasks**: Updating restarts the process; perform updates when idle.
- **Disabled on Dev Builds**: Versions like `dev` or suffixed `git describe` strings disable in-app updates to prevent overwriting local debug binaries.
- **Docker Note**: In-app updates inside Docker replace only the `artex` binary and do not update `artex-gateway`, `artex-sandbox`, or image toolchains; recreating containers restores the image version. Use `./update.sh` for full Docker upgrades.
- **Update Proxy (Optional)**: Configure a dedicated proxy (`http://`, `https://`, `socks5://`, `socks5h://`, with optional credentials) solely for version checks, checksums, and release downloads. Clear and save for direct connections, unaffected by global proxy or `HTTP_PROXY`/`HTTPS_PROXY`. Updates download strictly over HTTPS from GitHub domains.
- The proxy address is dialed by the **ARTEX server**. Inside Docker, `127.0.0.1` refers to the container itself; if the proxy runs on the host, use a container-reachable address (e.g. `http://host.docker.internal:7897` on Docker Desktop).
### Maintainers: Releasing via GitHub Actions
Release workflow: `.github/workflows/release.yml`. Pushing a release tag triggers the build, or re-run a failed release via **Actions → release → Run workflow** with an existing tag. Tags must match `vMAJOR.MINOR.PATCH` (e.g. `v0.3.17`) and be higher than currently deployed versions:
```bash
git push origin main
git tag v0.3.17
git push origin v0.3.17
```
The workflow pins the tagged commit, exports the frontend with Node.js 22, cross-compiles all five platform binaries with the Go version from `go.mod`, and produces zip archives plus `SHA256SUMS`. AMD64 and ARM64 Docker images are built on native runners and smoke-tested against a temporary PostgreSQL instance before publishing multi-arch version and `latest` tags (`artex`, `artex-gateway`, `artex-sandbox`). Once images succeed, archives and checksums are uploaded and the GitHub Release is published. Published releases cannot be overwritten—cut a new tag instead.
Configure repository Actions variable `ARTEX_DOCKER_IMAGE` (`<dockerhub-user>/<image>`) and secrets `DOCKERHUB_USERNAME` / `DOCKERHUB_TOKEN` under **Settings → Secrets and variables → Actions**. Release archives use `GITHUB_TOKEN`; credentials are never embedded in source code or images.
### Migrating an Existing Docker Deployment to This Repository's Images
Back up `.env`, Compose files, `data/`, and PostgreSQL while preserving the existing database volume and `skills` mount. Point `ARTEX_IMAGE` in `.env` to this repository's image and set `ARTEX_TAG`. If an older Compose file hardcodes the upstream image, add a `docker-compose.override.yml`:
```yaml
# docker-compose.override.yml
services:
artex:
image: ${ARTEX_IMAGE}:${ARTEX_TAG:-latest}
```
Then update only the application container:
```bash
docker compose pull artex
docker compose up -d --no-deps artex
curl --fail http://127.0.0.1:8787/api/health
docker compose logs --tail=50 artex
```
Keep the original deployment directory and Compose project name so `./data`, `./skills`, and the PostgreSQL volume remain attached. After migration, ARTEX checks `RuoJi6/ARTEX` for online updates.
For an initial binary-only migration of an existing ARM64 container (e.g. `artex-artex-1`), verify the downloaded zip against `SHA256SUMS`, back up `/app/artex`, and replace it:
```bash
sha256sum --ignore-missing --check SHA256SUMS
unzip artex-0.3.17-linux-arm64.zip
sudo docker stop artex-artex-1
sudo docker cp artex-artex-1:/app/artex ./artex-before-migration
sudo docker cp ./artex-0.3.17-linux-arm64/artex artex-artex-1:/app/artex
sudo docker start artex-artex-1
curl --fail http://127.0.0.1:8787/api/health
```
Replacements live in the container's writable layer and are lost when recreating the container; switch to this repository's images when rebuilding.
### Option 2: One-Click Upgrade & Rollback Script (Recommended)
```bash
cd ARTEX
./update.sh
```
Before every upgrade, the script automatically creates a rollback snapshot under `.artex-deploy/snapshots/<id>/` (containing `.env`, pinned local image ID tags `artex-rollback/*`, and a PostgreSQL logical dump `postgres.sql.gz`):
- **Upgrade Docker deployment**:
```bash
./update.sh --upgrade # Upgrade to latest images
./update.sh --upgrade --tag v0.3.33 # Upgrade to a specific version
```
Preserves `pgdata`, `./data`, and `./skills`, populates `ARTEX_HOST_DATA_DIR` / `ARTEX_GATEWAY_TOKEN` in `.env`, and safely adjusts non-root write permissions on `./data/tasks`, `./data/sessions`, and `./data/ephemeral` (skipping symlinks). Automatically rolls back to the pre-upgrade snapshot if the health check fails.
- **Roll back to a snapshot**:
```bash
./update.sh --list-snapshots # List available snapshots
./update.sh --rollback # Roll back to the latest snapshot
./update.sh --rollback <SNAP_ID> # Roll back to a specific snapshot
./update.sh --rollback <SNAP_ID> --restore-db # Also restore postgres.sql.gz from the snapshot
```
> Rollbacks prefer locally pinned exact image IDs (`artex-rollback/*`), working even offline or after `:latest` moves. Database schemas are forward/backward compatible so routine rollbacks rarely need `--restore-db`.
> Note: In Docker, in-app update/rollback affects only the `artex` control-plane binary and does not switch `artex-gateway` or `artex-sandbox` images; use `./update.sh` for full-stack upgrades and rollbacks.
### Option 3: Docker Compose (Manual)
```bash
cd ARTEX
git pull # Update compose / scripts (optional)
docker compose pull && docker pull "${ARTEX_SANDBOX_IMAGE:-ruoji6/artex-sandbox:latest}"
docker compose up -d --remove-orphans
```
### Option 4: Prebuilt Binaries (Releases)
Download the new zip from [Releases](https://github.com/RuoJi6/ARTEX/releases), stop the running process, overwrite `artex` and `skills/` (keeping `config.json` and `data/`), and restart:
```bash
cp -r <extracted-dir>/skills ./ && cp <extracted-dir>/artex ./
./start.sh
```
### Option 5: Build from Source
```bash
git pull
cd web && npm ci && npm run build:static && cd ..
mkdir -p server/webui/dist
cp -r web/out/. server/webui/dist
CGO_ENABLED=0 go build -tags embedui -o artex ./cmd/artex
# Restart ./start.sh
```
---
## Configuration
**Database** (`config.json`, or override via `ARTEX_PG_DSN`):
```json
{
"database": {
"host": "127.0.0.1", "port": 5432,
"user": "artex", "password": "yourpass",
"dbname": "artex", "sslmode": "disable"
}
}
```
**LLM**: `export ANTHROPIC_API_KEY=sk-...` (or `OPENAI_API_KEY`), or configure on the **LLM Configuration** page in the UI.
Optional: `ARTEX_LLM_PROVIDER` / `ARTEX_LLM_MODEL` / `ARTEX_LLM_BASE_URL` / `ARTEX_LLM_PROXY`.
**HTTP User-Agent**: Built-in WebFetch (worker / planner / main / chat), asset HTTP enrichment, egress connectivity probes, HTTP custom tools, Request Repeater, GitHub self-update, and optional `harvest_static.py` / `spider_mpa.py` pick randomly from 20 standard browser UA strings by default without exposing tool names. Go picks once per logical request and reuses it across redirects and direct-fallback retries; Python scripts pick once per execution. Override with `ARTEX_HTTP_USER_AGENT` (empty or invalid values fall back to random; restart or recreate container to apply). Explicit `--user-agent VALUE`, custom tool headers, and Repeater headers take precedence; explicit empty values still omit the header. Values are trimmed and must be printable ASCII. The recording proxy preserves existing UAs and explicit omissions. Randomizing UA does not alter TLS/cookie fingerprints and does not affect headless browsers, SDK web search, LLM/MCP/Webhook traffic, or standalone external tools.
See [HTTP_USER_AGENT.md](HTTP_USER_AGENT.md) for the full audit scope.
**Concurrency**: Configure per-task worker agent count in **System Settings** (default `3`).
**Common Flags**: `./start.sh -addr :8787 -proxy :8788` (`-addr` UI + API, `-proxy` traffic recording proxy). `start.sh` forwards all flags verbatim to `artex`.
### Optional HTTP Basic Auth
Under **System Settings → HTTP Basic Auth**, set a dedicated username and password, toggle **Enable access protection**, and save. Disabled by default; takes effect immediately without restarting. Passwords must be 8–72 bytes; usernames cannot contain `:`.
When enabled, visitors pass the browser's Basic Auth prompt before reaching the ARTEX login screen. Web pages, static assets, and APIs are all protected (except `/mcp`, which never accepts Basic Auth and uses Bearer access tokens—see **MCP Server** below). `GET`/`HEAD` `/api/health` also requires Basic Auth (`401` when unauthenticated; returns `{"ok":true}` without exposing app name or version when authenticated, without requiring an admin JWT). External probes must send Basic Auth credentials (e.g. `curl --fail --user '<user>' http://127.0.0.1:8787/api/health`). Version info is served by `/api/version` (requires admin JWT plus Basic Auth when enabled). Realm name is generic `Restricted`. Always use HTTPS on public networks.
When upgrading from older UIs that polled `/api/health` for version info, manually refresh the page after restart. Newer UIs poll `/api/version`.
Settings persist in PostgreSQL as bcrypt hashes (never echoed back); leaving the password blank preserves the existing password, and disabling retains credentials for quick re-enabling. An independent HttpOnly verification cookie lasts 12 hours and is compatible with JWT and SSE. Saving invalidates other browsers' verification cookies while keeping the active admin session valid.
If you forget the Basic Auth password, disable it in PostgreSQL and restart ARTEX:
```sql
UPDATE settings
SET value = jsonb_set(value::jsonb, '{enabled}', 'false'::jsonb)::text,
updated_at = now()
WHERE key = 'auth.http_basic';
```
### MCP Server (For External Agent Orchestration)
ARTEX can run as an MCP server allowing external agents (personal assistants, bots, etc.) to inspect tasks and findings, launch tasks, and pause or resume them.
Note the distinction: **System → MCP** manages external MCP servers that ARTEX's own agents *call*; this section describes the MCP endpoint that ARTEX *exposes*.
#### Enabling & Connecting
1. Enable **System Settings → System & Account → MCP Server**. Disabled by default (`/mcp` returns 404).
2. Click **Create Token** and select scopes. Tokens are shown once.
3. Configure your external agent:
| Field | Value |
| --- | --- |
| URL | `https://<your-artex-host>/mcp` |
| Transport | Streamable HTTP (stateless, responds with `application/json` only; no SSE, no stdio) |
| Auth | Header `Authorization: Bearer artex_mcp_...` |
```bash
curl -s https://artex.example.com/mcp \
-H 'Authorization: Bearer artex_mcp_xxx' -H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```
#### Not Protected by HTTP Basic Auth
`/mcp` **bypasses** HTTP Basic Auth and rejects Basic credentials, ARTEX login passwords, and admin JWTs—it accepts MCP Bearer tokens only (an HTTP request carries a single `Authorization` header). Use **Source Allowlist** below to restrict network access to `/mcp`, and always serve over HTTPS.
#### Source Allowlist
Enter allowed IPs or CIDRs (one per line, e.g. `203.0.113.7`, `10.0.0.0/8`, IPv6 supported) in the **Source Allowlist** field on the MCP Server card. Leave empty to allow any source.
- Checked before token validation; disallowed sources receive `403` along with the observed client IP for troubleshooting.
- Applies only to `/mcp`—never locks you out of the web UI or admin API.
- **Behind a Reverse Proxy**: Add your proxy IPs/CIDRs to **Trusted Proxies** so ARTEX extracts the first non-trusted IP from the right of `X-Forwarded-For`. Without trusted proxies configured, `X-Forwarded-For` is ignored to prevent spoofing. Configure Nginx with `proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;`.
- The card displays your current observed source IP to verify trusted proxy configuration.
#### Scopes & Tools
Tokens can list and invoke only tools within their granted scopes:
| Scope | Tools | Description |
| --- | --- | --- |
| `read` | `list_tasks` | List tasks (filterable by `company_id`, `category_id`, `status`) |
| `read` | `get_task` | Single task status, runtime, completed goals, finding counts (for polling) |
| `read` | `get_task_graph` | Overview of the task's Exploration Graph |
| `read` | `list_task_findings` | Confirmed findings for a task (without raw HTTP request/response bodies) |
| `read` | `list_companies` / `list_task_categories` / `list_llm_profiles` | Available companies, categories, and LLM profiles (without API keys) |
| `task:create` | `spawn_task` | Create and launch a task (supports `company_ids`, `category_id`) |
| `task:control` | `pause_task` / `resume_task` / `add_task_hint` | Pause, resume, or inject hints into a task |
ARTEX has no separate "project" entity—what external agents call a "project" maps to a company or task category.
Capabilities intentionally never exposed: creating/editing custom tools, MCP servers, or skills; reading/writing workspace files; LLM keys; system settings.
#### Token Restrictions
- **Company Scope**: Restricts the token to creating tasks under the selected companies (with targets within their asset scope) and viewing/controlling only those tasks. Other tasks appear non-existent. Pair with Asset Intercept rules for hard network-level enforcement.
- **Active Task Limit**: Cap on unfinished tasks (including paused/queued) created by the token.
- **Hourly Task Creation Limit**: Rolling 1-hour creation cap (deleted tasks still count).
- **Expiration & Revocation**: Revocation takes effect immediately and is irreversible.
#### Audit Log
Every tool call (including unauthorized/denied attempts) logs token, tool, arguments, outcome, error, source IP, and timestamp. Viewable under **Call Audit** in System Settings (retains the latest 20,000 entries).
#### Security Notes
- Creating tasks triggers real security testing—grant `task:create` only to trusted agents with tight company scopes and quotas.
- Task descriptions and finding summaries may include untrusted target content containing prompt injection.
- Cross-origin browser requests carrying an `Origin` header are rejected (`403`); `/mcp` sends no CORS headers.
### Reverse Proxy Deployment (HTTPS / Port 443 Only)
Both the frontend and API/SSE are served from the same backend port (default `:8787`), and the live activity stream connects to the **same origin** by default—**no `NEXT_PUBLIC_SSE_BASE` needed**. Expose port 443 publicly and keep `:8787` internal.
Because SSE is a long-lived streaming connection, **disable response buffering** in your reverse proxy or the browser will connect without receiving events (infinite spinner). Nginx example:
```nginx
server {
listen 443 ssl;
server_name your.domain.com;
# ssl_certificate / ssl_certificate_key ...
location / {
proxy_pass http://127.0.0.1:8787;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
# Essential for SSE: no buffering, long timeout, HTTP/1.1
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 3600s;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
# One-click backup / restore: allow large streaming uploads/downloads
location /api/system/backup/ {
proxy_pass http://127.0.0.1:8787;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
client_max_body_size 0;
proxy_request_buffering off;
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 3600s;
proxy_send_timeout 3600s;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
```
> Only set `NEXT_PUBLIC_SSE_BASE` at **build time** if SSE must use a different origin (e.g. a dedicated subdomain); it is baked into the static bundle during `next build` and has no effect at container runtime.
---
## Development
### AI-Driven Vulnerability Deduplication & Unified Reports
The Findings page defaults to **By Vulnerability**. Raw Findings, By Task, and By Asset views retain their existing tables, statuses, and actions, while merged records appear as expandable vulnerability folders. Within a task, the Reporter agent evaluates target, endpoint parameters, privilege boundaries, root cause, and verification evidence to automatically merge duplicate reports of the same underlying flaw—matching type or title alone is never sufficient. Findings with different severities, endpoints, or read/write impacts may still share a root cause, whereas sharing a login portal or token alone does not prove one. Ambiguous records remain independent with no manual merge-suggestion checkboxes. Folder `Crit/High/Med/Low` counters aggregate original reports (e.g. `0/1/1/1`); unique finding counts deduplicate by folder while severity breakdowns count original reports. Original content, severities, statuses, reports, and evidence are never overwritten.
Expand a folder arrow to inspect original findings, or click the folder title for the unified report, member findings, and merge history. Members can be removed manually if you disagree with an AI merge; removed pairs will not be re-merged automatically. Removing a member preserves the original finding and dissolves the folder once fewer than two members remain (retaining history). Inherited task groups remain read-only.
Newly reported findings generate standalone reports and undergo automatic duplicate checks. Existing historical records can be deduplicated in bulk via **AI Auto-Merge** on the Findings page or a task's **Findings** tab—no manual selection required. Historical cleanup reuses original reports read-only and validates root-cause verdicts (`merged` / `independent`) plus report completeness before finishing.
### Manual Vulnerability Retesting
Use the **Retests** tab in Task Detail, row-level **Retest** actions in Findings views, or **Start Retest** in Finding Detail to spawn an isolated `retester` agent session (with optional fix version, test conditions, or constraints) without restarting the parent scan. Verdicts are **Still Reproducible**, **Fixed**, or **Inconclusive**, recorded alongside evidence and session links. When a retest completes with verdict **Fixed**, the finding status automatically updates to `fixed` while preserving all original evidence and reports.
The built-in `retester` agent is created on first startup and can be customized (prompt, LLM, budget, tools) under Agent Management. Active retests on the same finding reuse the running session.
### Custom IP Probe Service
Under **System Settings → Traffic & Security → Custom IP Probe Service (Optional)**, configure any reachable HTTP/HTTPS endpoint returning either plain-text IP or `{"ip":"1.2.3.4"}` JSON. Supports intranet endpoints while blocking loopback, link-local, and cross-host redirects.
Once saved, the navbar egress IP display, proxy testing, proxy pool health checks, and auto-resume all use the custom endpoint without falling back to public services. Clear and save to restore the default `api.ipify.org` / `ifconfig.me`.
### Local Run & Testing
```bash
./dev.sh # Backend (:8787) + Traffic proxy (:8788) + Next.js dev (:5173) → http://localhost:5173
```
- Backend: `go run ./cmd/artex` (omitting `-tags embedui` runs without embedded frontend)
- Frontend: `cd web && npm run dev` (proxies `/api` to backend with HMR)
- Tests: `go test ./...`
- Mock Preview (no backend): `cd web && NEXT_PUBLIC_MOCK=1 npm run dev`
---
## System Architecture
ARTEX is an **LLM multi-agent autonomous penetration testing system**: a Go backend (with embedded Next.js frontend) + PostgreSQL, powered by the [`norma`](https://github.com/Autumn-27/norma) agent SDK (`agentcore` / `tool` / `permission` / `harness` / `memory` / `transcript`). Its core is a **Dual-Graph Architecture** paired with two autonomy mechanisms: **cross-worker process-level trace exchange** and a **shared multi-turn planner todolist** for stable multi-step exploit chains.
### Overall Layers
```mermaid
flowchart TB
subgraph FE["Frontend Next.js (go:embed single binary)"]
UI["Dashboard · Tasks · Assets · Coverage Graph · Traffic · Workspace · Settings"]
end
subgraph SRV["server (Go net/http)"]
API["REST /api/* JWT Auth SSE"]
ENG["engine scheduling loop"]
MGR["Manager Task / Engine / Store lifecycle"]
end
subgraph AG["agent (norma SDK)"]
GO["goals Goal decomposition & scope extraction"]
PL["planner Sole intent producer"]
WK["worker Executors ×N"]
MA["mainagent Human-in-the-loop"]
end
subgraph DB["PostgreSQL"]
AGRAPH["Asset Graph assets / companies / task_scope"]
EGRAPH["Exploration Graph exploration_nodes / anchors / activity"]
end
subgraph SUB["Supporting Subsystems"]
PROXY["Recording Proxy MITM + CA + Transparent Gateway"]
GUARD["guard / intercept Tool approval gate"]
ENR["enrich Async DNS / HTTP enrichment"]
EXT["MCP · skills · memory · report"]
end
UI -->|HTTP| API
API --> MGR --> ENG
ENG --> PL
ENG --> WK
API --> MA
API --> GO
PL --> DB
WK --> DB
MA --> DB
GO --> DB
WK -->|"Full Bash / HTTP / L4 capture"| PROXY
WK --> GUARD
WK --> ENR
PL -.-> EXT
WK -.-> EXT
MA -.-> EXT
```
| Layer | Responsibility |
| --- | --- |
| **Frontend** | Statically exported Next.js app embedded via `go:embed`; visualizes tasks, assets, exploration chains, coverage graphs, and human-in-the-loop chat |
| **server** | `net/http` routing + JWT auth + SSE; `Manager` owns task, engine, and DB store lifecycles |
| **engine** | One `plannerLoop` + N worker goroutines per task; intent claiming, timeouts, pause/drain |
| **agent** | `goals` / `planner` / `worker` / `mainagent`; `ToolSet` exposes both graphs as LLM tools |
| **db** | PostgreSQL persistence (`pgx`) for both graphs; idempotent `schema.sql` embedded via `go:embed` |
| **Subsystems** | Recording MITM proxy & transparent gateway, approval gate, async enrichment, MCP/skills/memory/reports |
### Dual-Graph Architecture: Exploration Graph + Asset Graph
ARTEX separates **what the targets are** from **how thoroughly they have been tested** into two independent graphs linked by anchors:
- **Asset Graph (Global Ground Truth)**: Shared across tasks. Nodes are `root_domain / subdomain / ip / service / app / endpoint` scoped to companies; parent-child hierarchy (`domain → subdomain → service → endpoint`) and deduplication keys are computed deterministically by code while agents submit raw observations.
- **Exploration Graph (Per-Task Reasoning Chain)**: Captures one task's reasoning and progress. Nodes are `goal / intent / fact / finding / hint`, linked via `spawns / derived_from / yields / proves` lineage edges answering which facts spawned which direction and what it proved.
- **Anchored Together**: `exploration_anchors(node_id, asset_id)` binds intents, facts, and findings to concrete assets—supporting both forward lookup (which assets an intent targets) and reverse lookup (which intents tested an asset and what facts emerged), powering **Asset Coverage** and the **Asset Coverage Graph**.
```mermaid
flowchart LR
subgraph EG["Exploration Graph (Per-Task Lineage)"]
direction TB
G["goal"]
I1["intent A"]
F1["fact"]
I2["intent B"]
FD["finding"]
G -->|spawns| I1
I1 -->|yields| F1
F1 -->|derived_from| I2
I2 -->|proves| FD
end
subgraph AG["Asset Graph (Global Truth)"]
direction TB
RD["root_domain"]
SD["subdomain"]
SV["service"]
EP["endpoint"]
RD --> SD --> SV --> EP
end
I1 -. anchor .-> SD
F1 -. anchor .-> SV
I2 -. anchor .-> EP
FD -. anchor .-> EP
```
> Division of labor: **planner** inspects exploration state, evaluates goals, and dispatches **intents** into the frontier only when uncovered directions exist; **worker** claims **one intent**, runs real tools, writes new assets/facts/findings back to both graphs, and stops.
### Engine & Intent Lifecycle (Closed Loop)
The engine runs an **event-driven** loop: graph mutations wake the planner, the planner dispatches intents, workers execute and write back, and those writes trigger the next cycle—until goals are proven (`prove_goal`).
```mermaid
sequenceDiagram
autonumber
participant EV as Graph Change Debounce
participant P as planner
participant FR as frontier Queue
participant W as worker
participant PX as Recording Proxy
participant DB as Dual Graphs + activity
EV-->>P: Wake up
P->>DB: Read state (graph_overview + coverage/scope)
P->>FR: Dispatch 0..N intents (with asset_ids)
Note over P,FR: Most wakeups dispatch 0 — stop if no new direction
W->>FR: claimNext() one intent
W->>DB: Load raw assets for asset_ids
W->>PX: Execute real tools (Sandbox / Bash / HTTP)
PX-->>W: Responses (fully captured + CA verified)
W->>DB: Write back fact / asset / finding + step activity
DB-->>EV: Graph mutated
EV-->>P: Wake up again (closed loop)
```
### Cross-Worker Process-Level Trace Exchange
During deep exploration, valuable clues (error messages, response snippets, hidden parameters) often appear inside a worker's **execution trace** without being promoted to formal facts. Workers can inspect peer traces directly:
- `search_all_worker_traces(q)`: Keyword-search other workers' execution traces within the same task (automatically excluding the caller's own intent), returning matches with `intent_id`;
- `list_worker_traces` / `get_worker_trace(intent_id, step_ids=[…])`: List prior workers and fetch exact steps for detailed inspection.
Information flows across workers at **execution-step granularity** while keeping each worker strictly scoped to its single claimed intent.
```mermaid
flowchart LR
WA["worker A (intent #12)"] -->|"step activity"| ACT[("Exploration Graph · activity store")]
WB["worker B (intent #34)"] -->|"step activity"| ACT
WC["worker C (intent #56)"] ==>|"1) search_all_worker_traces(q)"| ACT
ACT ==>|"2) matching A/B steps (self excluded)"| WC
WC ==>|"3) get_worker_trace(id, step_ids)"| ACT
ACT ==>|"4) full step details"| WC
```
### Shared Multi-Turn Planner Todolist → Stable Exploit Chains
Real exploit chains have strict dependencies (e.g. find injection → extract credentials → pivot → escalate privileges) and break if dispatched all at once in parallel. The planner therefore maintains a **task-scoped shared todolist** across stateless wakeups:
- Each planner wakeup starts a fresh LLM session; the shared todolist lets the planner **record a serial chain once** and dispatch intents **step-by-step as prerequisites are satisfied**;
- Each turn only dispatches the next step whose prerequisite facts exist and marks completed items accordingly.
```mermaid
flowchart TB
subgraph TODO["Shared Todolist (Per-Task · Persisted Across Wakeups)"]
direction LR
T1["1 Injection [Done]"]
T2["2 Extract Creds [In Progress]"]
T3["3 Lateral Move [Blocked]"]
T4["4 PrivEsc [Blocked]"]
T1 -.prereq met.-> T2 -.-> T3 -.-> T4
end
R1["Wakeup 1 → dispatch intent ①"] --> T1
R2["Wakeup 2 (① yields fact) → dispatch intent ②"] --> T2
R3["Wakeup 3 (② yields fact) → dispatch intent ③"] --> T3
```
This keeps multi-step attack chains **ordered, deduplicated, and resilient** despite event-driven stateless wakeups.
---
## Community
Scan to follow the WeChat Official Account **SecSentry** and send a direct message to join the community group.
<div align="center">
<img src="screenshots/wx.png" alt="WeChat Official Account SecSentry" width="480" />
</div>
---
## References
https://github.com/oritera/Cairn
## License & Disclaimer
### Open-Source License
This project is forked from [Autumn-27/ARTEX](https://github.com/Autumn-27/ARTEX) with original commit history and upstream attribution preserved, and is maintained by [ChainReactors](https://www.chainreactors.ai). For personal learning and academic research, it is licensed under the **GNU Affero General Public License v3.0 (AGPL-3.0)**—see [LICENSE](LICENSE) in the repository root for full terms.
Anyone may freely use, modify, and distribute this project, provided that **derivative works are also open-sourced under AGPL-3.0**; in particular, **if you modify this project and make it available to users over a network (such as an online service), you must provide the complete corresponding source code to those users**.
**Commercial Licensing & Partnerships**: To use this project in commercial or closed-source environments without AGPL-3.0 open-source obligations, contact [[email protected]](mailto:[email protected]).
**Contribution Notice**: By submitting a Pull Request, you agree that your contributions may be used under both AGPL-3.0 and the project's commercial license.
**ARTEX (forked from [Autumn-27/ARTEX](https://github.com/Autumn-27/ARTEX)), maintained by [ChainReactors](https://www.chainreactors.ai)**
> ⚠️ **Important Notice**: Open-source licenses themselves do not restrict field of use. The usage restrictions and disclaimer below represent additional terms and declarations from the authors—please abide by them strictly.
**ARTEX is strictly for personal learning, code research, and local technical verification. It must not be used to test any live online system or website.**
### Permitted Use
- Reading, studying, and researching the source code, and verifying technical concepts in **isolated local environments**;
- Non-offensive personal learning, academic research, and code review.
### Prohibited Conduct
- **Strictly prohibited from scanning, probing, exploiting, or attacking any website, live service, or networked system** (regardless of authorization or ownership);
- Strictly prohibited for real-world penetration testing, red/blue team exercises, or production environments;
- Strictly prohibited for unauthorized intrusion, data exfiltration, ransomware, denial of service, or any destructive/criminal activity;
- Strictly prohibited from violating any applicable laws or regulations in your jurisdiction.
### Legal Compliance
Users are solely responsible for complying with all applicable cybersecurity, data protection, and computer crime laws in their jurisdiction (including, in Mainland China, the Cybersecurity Law, Data Security Law, Personal Information Protection Law, and related judicial interpretations). **All legal liabilities and consequences arising from using this tool rest solely with the user.**
### Disclaimer
This project is provided **"AS IS"** without warranty of any kind, express or implied. The authors and contributors bear no liability for any direct or indirect damages, data loss, system disruption, or legal disputes resulting from using this tool (properly or improperly). **By downloading, installing, or using this project, you acknowledge that you have read, understood, and agreed to all terms above.**
### Task Intelligence
Enable **Agent Auto-Record** under **System Settings → Task Intelligence** to collect credentials, key leads, and sensitive data in a task's **Intelligence** tab. Disabled by default: when off, no intelligence tools, extra fields, or summary agents are injected, while existing records remain viewable. Enabling increases prompt and reporting token usage for subsequent agent runs; turning it off immediately rejects new server-side submissions.
Workers can invoke `record_intelligence` or attach an `intelligence` array to single/batch `record_fact` calls. Service `auth` entries submitted via `insert_assets` are automatically recorded as unverified credentials to prevent duplicate reports. Task and execution node bindings are enforced server-side, and records require authentic source evidence (obtaining credentials does not imply login success).
The UI supports category/title/reporter search, status filtering, pagination, status updates, and source inspection. Credential and sensitive-data payloads plus source evidence display inline without extra clicks. Inherited task records are clearly marked read-only; selecting an asset on the Assets page and clicking **Related Intelligence** opens the same record. Intelligence is included in task archive, restore, and delete operations (archive format v4, backward-compatible with v1–v3). Historical sessions are not retroactively re-extracted.
+81 -3
View File
@@ -7,6 +7,8 @@ import Link from "next/link";
import { import {
ActivityIcon, ActivityIcon,
BoxIcon, BoxIcon,
CheckIcon,
CopyIcon,
CpuIcon, CpuIcon,
ExternalLinkIcon, ExternalLinkIcon,
HardDriveIcon, HardDriveIcon,
@@ -15,7 +17,9 @@ import {
RotateCcwIcon, RotateCcwIcon,
SearchIcon, SearchIcon,
Settings2Icon, Settings2Icon,
ShieldCheckIcon,
SquareIcon, SquareIcon,
TerminalIcon,
Trash2Icon, Trash2Icon,
} from "lucide-react"; } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
@@ -87,7 +91,8 @@ export default function SandboxPage() {
const [saving, setSaving] = React.useState(false); const [saving, setSaving] = React.useState(false);
const [pruning, setPruning] = React.useState(false); const [pruning, setPruning] = React.useState(false);
const [busyKey, setBusyKey] = React.useState<string>(""); const [busyKey, setBusyKey] = React.useState<string>("");
const [upgradeTag, setUpgradeTag] = React.useState("v0.3.34");
const [copiedUpgradeCmd, setCopiedUpgradeCmd] = React.useState(false);
// Filters // Filters
const [scopeFilter, setScopeFilter] = React.useState<"all" | "task" | "session">("all"); const [scopeFilter, setScopeFilter] = React.useState<"all" | "task" | "session">("all");
const [stateFilter, setStateFilter] = React.useState<"all" | "running" | "stopped">("all"); const [stateFilter, setStateFilter] = React.useState<"all" | "running" | "stopped">("all");
@@ -165,6 +170,33 @@ export default function SandboxPage() {
void load(false, true, true); void load(false, true, true);
}, [load]); }, [load]);
React.useEffect(() => {
api
.version()
.then((v) => {
const raw = (v.version ?? "").trim().replace(/^v(?=\d)/, "");
if (/^\d+\.\d+\.\d+$/.test(raw)) {
setUpgradeTag(`v${raw}`);
}
})
.catch(() => {
// keep default release tag fallback
});
}, []);
const upgradeCommand = `git pull\n./update.sh --upgrade --tag ${upgradeTag}`;
const handleCopyUpgradeCommand = async () => {
try {
await navigator.clipboard.writeText(upgradeCommand);
setCopiedUpgradeCmd(true);
toast.success(L("升级命令已复制", "Upgrade command copied"));
window.setTimeout(() => setCopiedUpgradeCmd(false), 2000);
} catch {
toast.error(L("复制失败,请手动复制命令", "Copy failed, please copy manually"));
}
};
React.useEffect(() => { React.useEffect(() => {
if (!autoRefresh) return; if (!autoRefresh) return;
const timer = window.setInterval(() => { const timer = window.setInterval(() => {
@@ -351,8 +383,8 @@ export default function SandboxPage() {
`Manage lifecycle and resource usage for isolated task and chat containers (network: ${status.network}, ICC disabled).`, `Manage lifecycle and resource usage for isolated task and chat containers (network: ${status.network}, ICC disabled).`,
) )
: L( : L(
"当前为本地执行模式。部署时配置 ARTEX_SANDBOX_MODE=docker 即可启用任务与对话级容器隔离。", "当前为本地执行模式,请按下方命令在宿主机升级至沙箱隔离版以启用任务与对话级容器隔离。",
"Running in local execution mode. Set ARTEX_SANDBOX_MODE=docker to enable container isolation.", "Running in local execution mode. Use the host command below to upgrade to the Docker sandbox edition.",
)} )}
</p> </p>
</div> </div>
@@ -394,6 +426,52 @@ export default function SandboxPage() {
</div> </div>
) : null} ) : null}
{status && !status.enabled ? (
<Card className="border-amber-500/40 bg-amber-500/5">
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base">
<ShieldCheckIcon className="size-4 text-amber-600 dark:text-amber-400" />
{L("升级至沙箱隔离版(Sandbox)", "Upgrade to Sandbox Edition")}
</CardTitle>
<CardDescription>
{L(
"页面内「一键更新」仅替换容器内的 artex 主控程序,不会自动拉起 docker-socket-proxy、artex-gateway 透明网关与独立沙箱容器。请在宿主机原部署目录执行以下命令完成切换:",
"In-app updates only replace the artex binary inside the container and cannot start docker-socket-proxy, artex-gateway, or isolated sandbox containers. Run the following commands on the host in your deployment directory to switch:",
)}
</CardDescription>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex items-start justify-between gap-3 rounded-md border bg-background px-3.5 py-2.5">
<div className="flex min-w-0 items-start gap-2.5">
<TerminalIcon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
<pre className="overflow-x-auto font-mono text-foreground text-xs leading-relaxed">
<code>{upgradeCommand}</code>
</pre>
</div>
<Button
size="sm"
variant="outline"
className="h-7 shrink-0 gap-1.5 px-2.5 text-xs"
onClick={() => void handleCopyUpgradeCommand()}
>
{copiedUpgradeCmd ? (
<CheckIcon className="size-3.5 text-emerald-500" />
) : (
<CopyIcon className="size-3.5" />
)}
{copiedUpgradeCmd ? L("已复制", "Copied") : L("复制命令", "Copy")}
</Button>
</div>
<p className="text-muted-foreground text-xs leading-relaxed">
{L(
`升级会保留原有 PostgreSQL 数据、./data 与 ./skills,切换后无法回滚但会显著提高运行安全性。若非 git clone 部署,请先同步最新 docker-compose.yml、update.sh 与 scripts/ 后再执行 ./update.sh --upgrade --tag ${upgradeTag};完成后刷新本页即可进入 Docker 沙箱模式。`,
`Preserves PostgreSQL data, ./data, and ./skills. This switch is irreversible but significantly improves isolation security. If not deployed via git clone, sync the latest docker-compose.yml, update.sh, and scripts/ first, then run ./update.sh --upgrade --tag ${upgradeTag} and refresh this page.`,
)}
</p>
</CardContent>
</Card>
) : null}
{/* Summary KPI cards */} {/* Summary KPI cards */}
{status?.enabled ? ( {status?.enabled ? (
<div className="grid min-w-0 grid-cols-2 gap-3 lg:grid-cols-4"> <div className="grid min-w-0 grid-cols-2 gap-3 lg:grid-cols-4">
@@ -6,11 +6,14 @@ import Link from "next/link";
import { import {
BoxIcon, BoxIcon,
CheckIcon,
CopyIcon,
ExternalLinkIcon, ExternalLinkIcon,
PlayIcon, PlayIcon,
RefreshCwIcon, RefreshCwIcon,
RotateCcwIcon, RotateCcwIcon,
SquareIcon, SquareIcon,
TerminalIcon,
Trash2Icon, Trash2Icon,
} from "lucide-react"; } from "lucide-react";
import { toast } from "sonner"; import { toast } from "sonner";
@@ -53,7 +56,8 @@ export function SandboxCard() {
const [saving, setSaving] = React.useState(false); const [saving, setSaving] = React.useState(false);
const [pruning, setPruning] = React.useState(false); const [pruning, setPruning] = React.useState(false);
const [busyKey, setBusyKey] = React.useState(""); const [busyKey, setBusyKey] = React.useState("");
const [upgradeTag, setUpgradeTag] = React.useState("v0.3.34");
const [copiedUpgradeCmd, setCopiedUpgradeCmd] = React.useState(false);
const [image, setImage] = React.useState(""); const [image, setImage] = React.useState("");
const [memoryMB, setMemoryMB] = React.useState("2048"); const [memoryMB, setMemoryMB] = React.useState("2048");
const [cpus, setCpus] = React.useState("2"); const [cpus, setCpus] = React.useState("2");
@@ -102,6 +106,33 @@ export function SandboxCard() {
void load(true); void load(true);
}, [load]); }, [load]);
React.useEffect(() => {
api
.version()
.then((v) => {
const raw = (v.version ?? "").trim().replace(/^v(?=\d)/, "");
if (/^\d+\.\d+\.\d+$/.test(raw)) {
setUpgradeTag(`v${raw}`);
}
})
.catch(() => {
// keep default release tag fallback
});
}, []);
const upgradeCommand = `git pull && ./update.sh --upgrade --tag ${upgradeTag}`;
const handleCopyUpgradeCommand = async () => {
try {
await navigator.clipboard.writeText(upgradeCommand);
setCopiedUpgradeCmd(true);
toast.success(L("升级命令已复制", "Upgrade command copied"));
window.setTimeout(() => setCopiedUpgradeCmd(false), 2000);
} catch {
toast.error(L("复制失败,请手动复制命令", "Copy failed, please copy manually"));
}
};
const handleSave = async () => { const handleSave = async () => {
setSaving(true); setSaving(true);
try { try {
@@ -235,8 +266,8 @@ export function SandboxCard() {
`Docker sandbox isolation is active (network: ${status.network}, ICC disabled). Tasks and chat sessions execute tools in isolated non-root containers.`, `Docker sandbox isolation is active (network: ${status.network}, ICC disabled). Tasks and chat sessions execute tools in isolated non-root containers.`,
) )
: L( : L(
"当前为本地执行模式。部署时设置 ARTEX_SANDBOX_MODE=docker 即可启用任务级容器隔离。", "当前为本地执行模式,请在宿主机执行升级脚本切换至沙箱隔离版。",
"Running in local mode. Set ARTEX_SANDBOX_MODE=docker on deployment to enable per-task container isolation.", "Running in local mode. Run the host upgrade script to switch to the Docker sandbox edition.",
)} )}
</CardDescription> </CardDescription>
</CardHeader> </CardHeader>
@@ -248,6 +279,36 @@ export function SandboxCard() {
</div> </div>
) : null} ) : null}
{status && !status.enabled ? (
<div className="space-y-2 rounded-md border border-amber-500/40 bg-amber-500/5 p-3">
<p className="text-muted-foreground text-xs">
{L(
"在宿主机原部署目录执行以下命令升级至沙箱隔离版(保留数据库、./data 与 ./skills):",
"Run the following command on the host deployment directory to upgrade to the sandbox edition (preserves DB, ./data, and ./skills):",
)}
</p>
<div className="flex items-center justify-between gap-2 rounded border bg-background px-3 py-2">
<div className="flex min-w-0 items-center gap-2">
<TerminalIcon className="size-3.5 shrink-0 text-muted-foreground" />
<code className="overflow-x-auto font-mono text-foreground text-xs">{upgradeCommand}</code>
</div>
<Button
size="sm"
variant="outline"
className="h-7 shrink-0 gap-1 px-2 text-xs"
onClick={() => void handleCopyUpgradeCommand()}
>
{copiedUpgradeCmd ? (
<CheckIcon className="size-3.5 text-emerald-500" />
) : (
<CopyIcon className="size-3.5" />
)}
{copiedUpgradeCmd ? L("已复制", "Copied") : L("复制", "Copy")}
</Button>
</div>
</div>
) : null}
{status?.enabled ? ( {status?.enabled ? (
<> <>
<div className="grid grid-cols-1 gap-3 md:grid-cols-3"> <div className="grid grid-cols-1 gap-3 md:grid-cols-3">