mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-04 20:41:51 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
659e43e91e | ||
|
|
96a01bfeba | ||
|
|
efeb150f26 | ||
|
|
c49aa703c2 |
No files matched your search
@@ -130,6 +130,9 @@ jobs:
|
||||
GH_REPO: ${{ github.repository }}
|
||||
RELEASE_TAG: ${{ needs.prepare.outputs.tag }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.prepare.outputs.commit }}
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: pkg-*
|
||||
@@ -163,6 +166,30 @@ jobs:
|
||||
cat /tmp/artex-release.err >&2
|
||||
exit 1
|
||||
fi
|
||||
- name: Build release notes body
|
||||
env:
|
||||
DOCKER_IMAGE: ${{ vars.ARTEX_DOCKER_IMAGE }}
|
||||
run: |
|
||||
version="${RELEASE_TAG#v}"
|
||||
changelog_section="$(awk -v prefix="## [${version}]" '
|
||||
index($0, prefix) == 1 { found=1; next }
|
||||
found && index($0, "## [") == 1 { exit }
|
||||
found { print }
|
||||
' CHANGELOG.md | sed -e '/./,$!d')"
|
||||
{
|
||||
if [ -n "$changelog_section" ]; then
|
||||
printf '%s\n\n---\n\n' "$changelog_section"
|
||||
fi
|
||||
cat <<EOF
|
||||
### Docker Hub 镜像(Linux AMD64 / ARM64)
|
||||
|
||||
- 控制面:\`${DOCKER_IMAGE}:${RELEASE_TAG}\`(同时提供 \`latest\`)
|
||||
- 透明代理网关:\`${DOCKER_IMAGE}-gateway:${RELEASE_TAG}\`(同时提供 \`latest\`)
|
||||
- 沙箱执行环境:\`${DOCKER_IMAGE}-sandbox:${RELEASE_TAG}\`(同时提供 \`latest\`)
|
||||
|
||||
程序包提供 Linux、macOS 的 AMD64 / ARM64 及 Windows AMD64,并附 \`SHA256SUMS\`。部署、容器沙箱升级与在线更新说明见本仓库 README。
|
||||
EOF
|
||||
} > /tmp/release-body.md
|
||||
- uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.prepare.outputs.tag }}
|
||||
@@ -173,11 +200,7 @@ jobs:
|
||||
dist/*.zip
|
||||
dist/SHA256SUMS
|
||||
generate_release_notes: true
|
||||
body: |
|
||||
Docker Hub 镜像:`${{ vars.ARTEX_DOCKER_IMAGE }}:${{ needs.prepare.outputs.tag }}`,同时提供 `latest`。
|
||||
支持 Linux AMD64 / ARM64,Docker 会自动选择宿主机架构。
|
||||
程序包提供 Linux、macOS 的 AMD64 / ARM64 及 Windows AMD64,并附 SHA256SUMS。
|
||||
部署和在线更新说明见本仓库 README。
|
||||
body_path: /tmp/release-body.md
|
||||
- name: Publish complete release
|
||||
run: gh release edit "$RELEASE_TAG" --draft=false --latest
|
||||
|
||||
|
||||
@@ -4,6 +4,27 @@
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.3.35] - 2026-12-04
|
||||
|
||||
### 核心架构亮点(容器化沙箱与透明代理网关)
|
||||
|
||||
- **任务/对话级容器沙箱隔离(`artex-sandbox`)**:每个任务与对话在独立非 root Docker 容器中运行 Bash、脚本与 Playwright 浏览器;主控通过 `docker-socket-proxy` 最小权限管理容器,沙箱网桥禁用容器间互通(`enable_icc=false`),支持内存/CPU/PIDs/SHM 限额与闲置/完结自动停机。
|
||||
- **全流量透明代理网关(`artex-gateway`)**:采用 TUN + gVisor netstack(含策略路由自愈)在宿主机网络层统一接管沙箱 TCP / DNS / UDP / ICMP 流量,硬阻断沙箱直连外网 NAT;启用代理或代理池后自动通过上游代理转发原始 TCP 与 DNS-over-TCP,并默认阻断直连 UDP/ICMP 防止泄露真实出口 IP。
|
||||
- **代理池与单容器级路由控制**:支持代理池定时轮换、健康检查冷却、故障切换与全池异常自动暂停续跑,并支持按任务/对话/定时任务容器维度独立设置出口策略(继承全局代理池、绑定指定代理节点、自定义代理或直连)。
|
||||
|
||||
### 本版本新增与改进
|
||||
|
||||
- **宿主机沙箱升级命令完善与旧编排拦截**:沙箱容器页与系统设置沙箱卡片在本地模式下区分展示 **git clone 部署**(`git pull --ff-only && ./update.sh --upgrade --tag <version> --skip-git-pull`)与 **非 git 部署**(自动备份旧 `docker-compose.yml` 并同步对应版本编排与脚本)两套一键复制命令;`scripts/deploy-lib.sh` 新增 `validate_sandbox_compose` 校验,拦截缺少 `docker-socket-proxy` / `artex-gateway` / `ARTEX_SANDBOX_MODE` 的旧版 2 服务 `docker-compose.yml`,并在部署快照中同步备份与回滚 `docker-compose.yml`。
|
||||
- **Shell 脚本按系统时区自动切换中英文**:`install.sh`、`update.sh`、`scripts/deploy-lib.sh`、`start.sh`、`build.sh`、`dev.sh`、`reset-password.sh` 按宿主机时区自动选择中文或英文输出(大中华区时区输出中文,其余时区输出英文,并支持 `ARTEX_LANG=zh|en` 显式覆盖)。
|
||||
- **更新弹窗与发布说明优化**:系统设置「版本与更新」弹窗中的「单容器版 → 沙箱隔离版」不可回滚提示改为仅在 Docker 非沙箱模式下显示,避免已是沙箱隔离版的用户在后续常规升级时看到误导提示;GitHub Release 工作流自动提取 `CHANGELOG.md` 对应版本说明并附带 `artex` / `artex-gateway` / `artex-sandbox` 三套多架构镜像信息。
|
||||
|
||||
## [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
|
||||
|
||||
### 新增与改进
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
AI 自主渗透测试系统(Go 后端 + Next.js 前端)
|
||||
|
||||
**简体中文** | [English](README_EN.md)
|
||||
|
||||
<p>
|
||||
<a href="https://www.chainreactors.ai" target="_blank" rel="noopener noreferrer">
|
||||
<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/)。
|
||||
|
||||
+761
@@ -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 |
|
||||
| :---: | :---: |
|
||||
|  |  |
|
||||
|
||||
| Task Execution (Sessions / Tool Calls) | Exploration Graph |
|
||||
| :---: | :---: |
|
||||
|  |  |
|
||||
|
||||
| Findings | Assets |
|
||||
| :---: | :---: |
|
||||
|  |  |
|
||||
|
||||
| Asset Coverage Graph (Force-Directed · Tested Highlight · Collapse/Expand) |
|
||||
| :---: |
|
||||
|  |
|
||||
|
||||
| Traffic Recording | Human-in-the-Loop Chat |
|
||||
| :---: | :---: |
|
||||
|  |  |
|
||||
|
||||
| Agent Management | LLM Configuration |
|
||||
| :---: | :---: |
|
||||
|  |  |
|
||||
|
||||
| Intercept Approvals | Backend Logs |
|
||||
| :---: | :---: |
|
||||
|  |  |
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
@@ -22,13 +22,12 @@ set -euo pipefail
|
||||
|
||||
cd "$(cd "$(dirname "$0")" && pwd)"
|
||||
|
||||
info() { printf '\033[36m[*]\033[0m %s\n' "$*"; }
|
||||
ok() { printf '\033[32m[+]\033[0m %s\n' "$*"; }
|
||||
warn() { printf '\033[33m[!]\033[0m %s\n' "$*" >&2; }
|
||||
die() { printf '\033[31m[x]\033[0m %s\n' "$*" >&2; exit 1; }
|
||||
# shellcheck source=scripts/deploy-lib.sh
|
||||
. ./scripts/deploy-lib.sh
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
if [ "$ARTEX_SCRIPT_LANG" = "zh" ]; then
|
||||
cat <<'EOF'
|
||||
用法:
|
||||
./build.sh 编译当前系统当前架构
|
||||
./build.sh --target linux/amd64 编译一个指定目标
|
||||
@@ -44,6 +43,24 @@ usage() {
|
||||
多目标列表可通过 ARTEX_TARGETS 覆盖,例如:
|
||||
ARTEX_TARGETS=linux/amd64,windows/amd64 ./build.sh --release
|
||||
EOF
|
||||
else
|
||||
cat <<'EOF'
|
||||
Usage:
|
||||
./build.sh Build for current OS/ARCH
|
||||
./build.sh --target linux/amd64 Build for a specific target
|
||||
./build.sh --release Build and package all supported targets
|
||||
|
||||
Options:
|
||||
--release Build amd64/arm64 targets for Linux, macOS, Windows and create zips
|
||||
--target OS/ARCH Set a single target, e.g. windows/amd64
|
||||
--upx Require UPX binary compression (may affect some Linux environments)
|
||||
--no-compress Skip UPX; use Go linker stripping and zip compression only
|
||||
--help Show this help
|
||||
|
||||
Override target list via ARTEX_TARGETS, e.g.:
|
||||
ARTEX_TARGETS=linux/amd64,windows/amd64 ./build.sh --release
|
||||
EOF
|
||||
fi
|
||||
}
|
||||
|
||||
RELEASE_TARGETS_DEFAULT="linux/amd64,linux/arm64,darwin/amd64,darwin/arm64,windows/amd64"
|
||||
@@ -59,7 +76,7 @@ while [ "$#" -gt 0 ]; do
|
||||
shift
|
||||
;;
|
||||
--target)
|
||||
[ "$#" -ge 2 ] || die "--target 需要 OS/ARCH 参数"
|
||||
[ "$#" -ge 2 ] || die_l "--target 需要 OS/ARCH 参数" "--target requires an OS/ARCH value"
|
||||
target_arg="$2"
|
||||
case "$target_arg" in
|
||||
*/*)
|
||||
@@ -67,7 +84,7 @@ while [ "$#" -gt 0 ]; do
|
||||
ARTEX_TARGET_ARCH="${target_arg##*/}"
|
||||
ARTEX_TARGETS="$target_arg"
|
||||
;;
|
||||
*) die "目标必须是 OS/ARCH,例如 linux/amd64" ;;
|
||||
*) die_l "目标必须是 OS/ARCH,例如 linux/amd64" "Target must be OS/ARCH, e.g. linux/amd64" ;;
|
||||
esac
|
||||
shift 2
|
||||
;;
|
||||
@@ -83,12 +100,11 @@ while [ "$#" -gt 0 ]; do
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*) die "未知参数:$1(使用 --help 查看用法)" ;;
|
||||
*) die_l "未知参数:$1(使用 --help 查看用法)" "Unknown option: $1 (use --help for usage)" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
command -v go >/dev/null 2>&1 || die "未检测到 Go(项目需要 Go 1.26 或更高版本)"
|
||||
|
||||
command -v go >/dev/null 2>&1 || die_l "未检测到 Go(项目需要 Go 1.26 或更高版本)" "Go not found (Go 1.26 or newer is required)"
|
||||
ARTEX_GOSUMDB="${ARTEX_GOSUMDB:-sum.golang.org}"
|
||||
if [ -z "${ARTEX_BUILD_VERSION:-}" ]; then
|
||||
if command -v git >/dev/null 2>&1 && git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
@@ -112,16 +128,16 @@ else
|
||||
fi
|
||||
|
||||
if [ "${ARTEX_SKIP_FRONTEND:-0}" = "1" ]; then
|
||||
[ -d server/webui/dist ] || die "ARTEX_SKIP_FRONTEND=1 但 server/webui/dist 不存在"
|
||||
[ -d server/webui/dist ] || die_l "ARTEX_SKIP_FRONTEND=1 但 server/webui/dist 不存在" "ARTEX_SKIP_FRONTEND=1 but server/webui/dist does not exist"
|
||||
else
|
||||
command -v npm >/dev/null 2>&1 || die "未检测到 npm(前端静态构建需要 Node.js/npm)"
|
||||
command -v rsync >/dev/null 2>&1 || die "未检测到 rsync"
|
||||
info "构建前端静态资源"
|
||||
command -v npm >/dev/null 2>&1 || die_l "未检测到 npm(前端静态构建需要 Node.js/npm)" "npm not found (Node.js/npm is required for static frontend build)"
|
||||
command -v rsync >/dev/null 2>&1 || die_l "未检测到 rsync" "rsync not found"
|
||||
info_l "构建前端静态资源" "Building static frontend assets"
|
||||
if [ "${ARTEX_SKIP_NPM_CI:-0}" != "1" ]; then
|
||||
(cd web && npm ci)
|
||||
fi
|
||||
(cd web && npm run build:static)
|
||||
info "同步前端资源到 server/webui/dist"
|
||||
info_l "同步前端资源到 server/webui/dist" "Syncing frontend assets to server/webui/dist"
|
||||
mkdir -p server/webui/dist
|
||||
rsync -a --delete web/out/ server/webui/dist/
|
||||
fi
|
||||
@@ -131,18 +147,18 @@ compress_binary() {
|
||||
goos="$2"
|
||||
case "$ARTEX_COMPRESS" in
|
||||
0|off|false|none)
|
||||
info "跳过 UPX:$binary"
|
||||
info_l "跳过 UPX:$binary" "Skipping UPX: $binary"
|
||||
return 0
|
||||
;;
|
||||
auto|required|true|1) ;;
|
||||
*) die "ARTEX_COMPRESS 必须是 off、auto 或 required" ;;
|
||||
*) die_l "ARTEX_COMPRESS 必须是 off、auto 或 required" "ARTEX_COMPRESS must be off, auto, or required" ;;
|
||||
esac
|
||||
|
||||
if ! command -v upx >/dev/null 2>&1; then
|
||||
if [ "$ARTEX_COMPRESS" = "required" ]; then
|
||||
die "ARTEX_COMPRESS=required 但未检测到 upx"
|
||||
die_l "ARTEX_COMPRESS=required 但未检测到 upx" "ARTEX_COMPRESS=required but upx was not found"
|
||||
fi
|
||||
warn "未检测到 upx,保留 linker 压缩结果:$binary"
|
||||
warn_l "未检测到 upx,保留 linker 压缩结果:$binary" "upx not found; keeping linker-stripped binary: $binary"
|
||||
return 0
|
||||
fi
|
||||
|
||||
@@ -152,13 +168,13 @@ compress_binary() {
|
||||
# shellcheck disable=SC2086
|
||||
if ! upx $upx_args -- "$binary"; then
|
||||
if [ "$ARTEX_COMPRESS" = "required" ]; then
|
||||
die "UPX 压缩失败:$binary"
|
||||
die_l "UPX 压缩失败:$binary" "UPX compression failed: $binary"
|
||||
fi
|
||||
warn "UPX 不支持该目标格式,保留未压缩二进制:$binary"
|
||||
warn_l "UPX 不支持该目标格式,保留未压缩二进制:$binary" "UPX does not support this target; keeping uncompressed binary: $binary"
|
||||
return 0
|
||||
fi
|
||||
after=$(wc -c < "$binary" | tr -d ' ')
|
||||
ok "UPX 压缩完成:$binary (${before} -> ${after} bytes)"
|
||||
ok_l "UPX 压缩完成:$binary (${before} -> ${after} bytes)" "UPX compression complete: $binary (${before} -> ${after} bytes)"
|
||||
}
|
||||
|
||||
package_binary() {
|
||||
@@ -169,7 +185,7 @@ package_binary() {
|
||||
package_root="${ARTEX_PACKAGE_DIR}/${package_name}"
|
||||
archive="${ARTEX_PACKAGE_DIR}/${package_name}.zip"
|
||||
|
||||
command -v zip >/dev/null 2>&1 || die "打包需要 zip"
|
||||
command -v zip >/dev/null 2>&1 || die_l "打包需要 zip" "zip is required for packaging"
|
||||
rm -rf "$package_root" "$archive"
|
||||
mkdir -p "$package_root"
|
||||
cp "$binary" "$package_root/"
|
||||
@@ -186,20 +202,20 @@ package_binary() {
|
||||
if [ -f README.md ]; then cp README.md "$package_root/"; fi
|
||||
(cd "$ARTEX_PACKAGE_DIR" && zip -q -r -9 "$(basename "$archive")" "$(basename "$package_root")")
|
||||
rm -rf "$package_root"
|
||||
ok "Release 压缩包:$archive"
|
||||
ok_l "Release 压缩包:$archive" "Release archive: $archive"
|
||||
}
|
||||
|
||||
build_target() {
|
||||
target="$1"
|
||||
case "$target" in
|
||||
*/*) ;;
|
||||
*) die "无效目标:$target(必须是 OS/ARCH)" ;;
|
||||
*) die_l "无效目标:$target(必须是 OS/ARCH)" "Invalid target: $target (must be OS/ARCH)" ;;
|
||||
esac
|
||||
goos="${target%%/*}"
|
||||
goarch="${target##*/}"
|
||||
case "$goos" in
|
||||
linux|darwin|windows) ;;
|
||||
*) die "不支持的系统:$goos(支持 linux、darwin、windows)" ;;
|
||||
*) die_l "不支持的系统:$goos(支持 linux、darwin、windows)" "Unsupported OS: $goos (supported: linux, darwin, windows)" ;;
|
||||
esac
|
||||
|
||||
binary_name="artex"
|
||||
@@ -211,7 +227,7 @@ build_target() {
|
||||
fi
|
||||
mkdir -p "$(dirname "$output")"
|
||||
|
||||
info "编译 ${goos}/${goarch},版本 ${ARTEX_BUILD_VERSION}"
|
||||
info_l "编译 ${goos}/${goarch},版本 ${ARTEX_BUILD_VERSION}" "Building ${goos}/${goarch}, version ${ARTEX_BUILD_VERSION}"
|
||||
GOSUMDB="$ARTEX_GOSUMDB" \
|
||||
CGO_ENABLED=0 \
|
||||
GOOS="$goos" \
|
||||
@@ -226,7 +242,7 @@ build_target() {
|
||||
compress_binary "$output" "$goos"
|
||||
if command -v file >/dev/null 2>&1; then file "$output"; fi
|
||||
if [ "$ARTEX_PACKAGE" = "1" ]; then package_binary "$output" "$goos" "$goarch"; fi
|
||||
ok "编译完成:$output"
|
||||
ok_l "编译完成:$output" "Build complete: $output"
|
||||
}
|
||||
|
||||
write_checksums() {
|
||||
@@ -237,10 +253,10 @@ write_checksums() {
|
||||
elif command -v shasum >/dev/null 2>&1; then
|
||||
(cd "$ARTEX_PACKAGE_DIR" && for archive in *.zip; do shasum -a 256 "$archive"; done > "$(basename "$checksum_file")")
|
||||
else
|
||||
warn "未检测到 sha256sum 或 shasum,跳过 SHA256SUMS"
|
||||
warn_l "未检测到 sha256sum 或 shasum,跳过 SHA256SUMS" "Neither sha256sum nor shasum found; skipping SHA256SUMS"
|
||||
return 0
|
||||
fi
|
||||
ok "校验文件:$checksum_file"
|
||||
ok_l "校验文件:$checksum_file" "Checksums written: $checksum_file"
|
||||
}
|
||||
|
||||
mkdir -p "$ARTEX_OUTPUT_DIR"
|
||||
@@ -250,7 +266,7 @@ old_ifs="$IFS"
|
||||
IFS=','
|
||||
read -r -a targets <<< "$ARTEX_TARGETS"
|
||||
IFS="$old_ifs"
|
||||
[ "${#targets[@]}" -gt 0 ] || die "ARTEX_TARGETS 不能为空"
|
||||
[ "${#targets[@]}" -gt 0 ] || die_l "ARTEX_TARGETS 不能为空" "ARTEX_TARGETS cannot be empty"
|
||||
for target in "${targets[@]}"; do
|
||||
target="${target//[[:space:]]/}"
|
||||
[ -n "$target" ] || continue
|
||||
@@ -259,5 +275,5 @@ done
|
||||
|
||||
if [ "$ARTEX_PACKAGE" = "1" ]; then
|
||||
write_checksums
|
||||
info "Release 包已生成于:$ARTEX_PACKAGE_DIR"
|
||||
info_l "Release 包已生成于:$ARTEX_PACKAGE_DIR" "Release archives generated in: $ARTEX_PACKAGE_DIR"
|
||||
fi
|
||||
@@ -6,6 +6,9 @@
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
# shellcheck source=scripts/deploy-lib.sh
|
||||
. ./scripts/deploy-lib.sh
|
||||
|
||||
# 退出时结束本进程组内的所有子进程(后端 + 前端)。
|
||||
cleanup() { kill 0 2>/dev/null || true; }
|
||||
trap cleanup EXIT INT TERM
|
||||
@@ -16,5 +19,5 @@ go run ./cmd/artex -addr :8787 -proxy 127.0.0.1:8788 &
|
||||
# 前端热更新(Vite/Next dev server,/api 反代到 :8787)。
|
||||
( cd web && npm run dev ) &
|
||||
|
||||
echo "[dev] 后端 :8787 / 代理 :8788 / 前端 http://localhost:5173 (Ctrl-C 退出)"
|
||||
echo "$(msg '[dev] 后端 :8787 / 代理 :8788 / 前端 http://localhost:5173 (Ctrl-C 退出)' '[dev] Backend :8787 / Proxy :8788 / Frontend http://localhost:5173 (Ctrl-C to exit)')"
|
||||
wait
|
||||
+60
-41
@@ -16,20 +16,22 @@ cd "$(cd "$(dirname "$0")" && pwd)"
|
||||
# ── docker 环境检测 / 自动安装 ───────────────────
|
||||
ensure_docker(){
|
||||
if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then
|
||||
ok "已检测到 docker 与 docker compose"; return
|
||||
ok_l "已检测到 docker 与 docker compose" "Detected docker and docker compose"; return
|
||||
fi
|
||||
warn "未检测到 docker / docker compose"
|
||||
warn_l "未检测到 docker / docker compose" "docker / docker compose not found"
|
||||
case "$(uname -s)" in
|
||||
Linux)
|
||||
if [ "$(ask '自动安装 Docker? (y/n)' y)" = y ]; then
|
||||
if is_yes "$(ask_l '自动安装 Docker? (y/n)' 'Install Docker automatically? (y/n)' y)"; then
|
||||
curl -fsSL https://get.docker.com | sh
|
||||
sudo usermod -aG docker "$USER" || true
|
||||
ok "Docker 安装完成(用户组变更需重新登录后免 sudo)"
|
||||
ok_l "Docker 安装完成(用户组变更需重新登录后免 sudo)" \
|
||||
"Docker installed (re-login for docker group membership to take effect without sudo)"
|
||||
else
|
||||
die "请自行安装 docker 后重试"
|
||||
die_l "请自行安装 docker 后重试" "Please install Docker manually and retry"
|
||||
fi ;;
|
||||
Darwin) die "macOS 请安装 Docker Desktop:https://www.docker.com/products/docker-desktop/" ;;
|
||||
*) die "请自行安装 docker 后重试" ;;
|
||||
Darwin) die_l "macOS 请安装 Docker Desktop:https://www.docker.com/products/docker-desktop/" \
|
||||
"On macOS, please install Docker Desktop: https://www.docker.com/products/docker-desktop/" ;;
|
||||
*) die_l "请自行安装 docker 后重试" "Please install Docker manually and retry" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
@@ -38,7 +40,7 @@ install_docker(){
|
||||
local tag="${1:-}"
|
||||
ensure_docker
|
||||
preflight_docker
|
||||
|
||||
validate_sandbox_compose "$COMPOSE_FILE" "$tag"
|
||||
umask 077
|
||||
local is_fresh=0
|
||||
[ -f .env ] || is_fresh=1
|
||||
@@ -47,40 +49,41 @@ install_docker(){
|
||||
|
||||
if [ "$is_fresh" -eq 1 ] && [ "${ARTEX_NONINTERACTIVE:-0}" != "1" ]; then
|
||||
local key
|
||||
key="$(ask 'ANTHROPIC_API_KEY(可留空,后续在 UI 配)' '')"
|
||||
key="$(ask_l 'ANTHROPIC_API_KEY(可留空,后续在 UI 配)' 'ANTHROPIC_API_KEY (optional, can be set later in UI)' '')"
|
||||
[ -n "$key" ] && env_set ANTHROPIC_API_KEY "$key" .env
|
||||
fi
|
||||
|
||||
pull_docker_images
|
||||
info "启动服务(${COMPOSE_FILE})…"
|
||||
info_l "启动服务(${COMPOSE_FILE})…" "Starting services (${COMPOSE_FILE})..."
|
||||
docker compose -f "$COMPOSE_FILE" up -d --remove-orphans
|
||||
wait_for_health "$COMPOSE_FILE" || warn "服务仍在启动中,请执行 docker compose -f ${COMPOSE_FILE} logs -f artex 观察"
|
||||
wait_for_health "$COMPOSE_FILE" || warn_l "服务仍在启动中,请执行 docker compose -f ${COMPOSE_FILE} logs -f artex 观察" \
|
||||
"Service is still starting; watch logs with: docker compose -f ${COMPOSE_FILE} logs -f artex"
|
||||
|
||||
ok "启动完成 → http://localhost:8787"
|
||||
info "查看日志:docker compose -f ${COMPOSE_FILE} logs -f artex"
|
||||
info "后续升级 / 回滚:./update.sh"
|
||||
ok_l "启动完成 → http://localhost:8787" "Started -> http://localhost:8787"
|
||||
info_l "查看日志:docker compose -f ${COMPOSE_FILE} logs -f artex" "View logs: docker compose -f ${COMPOSE_FILE} logs -f artex"
|
||||
info_l "后续升级 / 回滚:./update.sh" "Future upgrades / rollbacks: ./update.sh"
|
||||
}
|
||||
|
||||
# ── ② 本地编译运行 ──────────────────────────────
|
||||
install_local(){
|
||||
echo "数据库安装方式:"
|
||||
echo " 1) 连接已有 PostgreSQL"
|
||||
echo " 2) 用 Docker 起一个 PostgreSQL(需要 docker)"
|
||||
case "$(ask '选择' 1)" in
|
||||
echo "$(msg '数据库安装方式:' 'PostgreSQL setup:')"
|
||||
echo "$(msg ' 1) 连接已有 PostgreSQL' ' 1) Connect to an existing PostgreSQL')"
|
||||
echo "$(msg ' 2) 用 Docker 起一个 PostgreSQL(需要 docker)' ' 2) Start a PostgreSQL container via Docker (requires docker)')"
|
||||
case "$(ask_l '选择' 'Select' 1)" in
|
||||
2)
|
||||
ensure_docker
|
||||
local pw; pw="$(ask 'Postgres 密码(回车随机)' "$(rand)")"
|
||||
local pw; pw="$(ask_l 'Postgres 密码(回车随机)' 'Postgres password (Enter to auto-generate)' "$(rand)")"
|
||||
docker run -d --name artex-pg -p 5432:5432 \
|
||||
-e POSTGRES_USER=artex -e POSTGRES_PASSWORD="$pw" -e POSTGRES_DB=artex \
|
||||
-v artex-pg:/var/lib/postgresql/data postgres:16-alpine
|
||||
DB_HOST=127.0.0.1 DB_PORT=5432 DB_USER=artex DB_PASS="$pw" DB_NAME=artex DB_SSL=disable ;;
|
||||
*)
|
||||
DB_HOST="$(ask '数据库地址' 127.0.0.1)"
|
||||
DB_PORT="$(ask '端口' 5432)"
|
||||
DB_USER="$(ask '账号' artex)"
|
||||
DB_PASS="$(ask '密码' '')"
|
||||
DB_NAME="$(ask '数据库名' artex)"
|
||||
DB_SSL="$(ask 'sslmode (disable/require)' disable)" ;;
|
||||
DB_HOST="$(ask_l '数据库地址' 'Database host' 127.0.0.1)"
|
||||
DB_PORT="$(ask_l '端口' 'Port' 5432)"
|
||||
DB_USER="$(ask_l '账号' 'Username' artex)"
|
||||
DB_PASS="$(ask_l '密码' 'Password' '')"
|
||||
DB_NAME="$(ask_l '数据库名' 'Database name' artex)"
|
||||
DB_SSL="$(ask_l 'sslmode (disable/require)' 'sslmode (disable/require)' disable)" ;;
|
||||
esac
|
||||
|
||||
cat > config.json <<JSON
|
||||
@@ -95,39 +98,55 @@ install_local(){
|
||||
}
|
||||
}
|
||||
JSON
|
||||
ok "已生成 config.json"
|
||||
ok_l "已生成 config.json" "Generated config.json"
|
||||
|
||||
command -v go >/dev/null 2>&1 || die "未检测到 Go,请先安装 Go(>=1.26):https://go.dev/dl/"
|
||||
command -v go >/dev/null 2>&1 || die_l "未检测到 Go,请先安装 Go(>=1.26):https://go.dev/dl/" \
|
||||
"Go not found; please install Go (>=1.26): https://go.dev/dl/"
|
||||
ok "Go: $(go version)"
|
||||
|
||||
if command -v npm >/dev/null 2>&1; then
|
||||
info "构建前端静态产物…"
|
||||
info_l "构建前端静态产物…" "Building static frontend assets..."
|
||||
( cd web && npm ci && npm run build:static )
|
||||
rm -rf server/webui/dist && cp -r web/out server/webui/dist
|
||||
info "编译内嵌单二进制…"
|
||||
info_l "编译内嵌单二进制…" "Building embedded single binary..."
|
||||
CGO_ENABLED=0 go build -tags embedui -trimpath -o artex ./cmd/artex
|
||||
else
|
||||
warn "未检测到 npm:将编译**不内嵌前端**的后端(前端需另跑 npm run dev)"
|
||||
warn_l "未检测到 npm:将编译**不内嵌前端**的后端(前端需另跑 npm run dev)" \
|
||||
"npm not found: building backend WITHOUT embedded frontend (run npm run dev separately)"
|
||||
CGO_ENABLED=0 go build -o artex ./cmd/artex
|
||||
fi
|
||||
ok "编译完成 → ./artex"
|
||||
ok_l "编译完成 → ./artex" "Build complete -> ./artex"
|
||||
|
||||
info "启动…(Ctrl-C 退出)"
|
||||
info_l "启动…(Ctrl-C 退出)" "Starting... (Ctrl-C to exit)"
|
||||
./start.sh
|
||||
}
|
||||
|
||||
usage(){
|
||||
cat <<'USAGE'
|
||||
if [ "$ARTEX_SCRIPT_LANG" = "zh" ]; then
|
||||
cat <<'USAGE'
|
||||
用法: ./install.sh [选项]
|
||||
|
||||
选项:
|
||||
--docker 直接执行 Docker 部署(docker-compose.yml)
|
||||
--tag <TAG> 指定镜像版本 tag(如 v0.3.33 / latest)
|
||||
--tag <TAG> 指定镜像版本 tag(如 v0.3.34 / latest)
|
||||
--local 使用本地 Go 编译运行
|
||||
--skip-pull 跳过镜像拉取(适用于本地已构建镜像)
|
||||
-y, --yes 非交互模式(自动填充默认值)
|
||||
-h, --help 显示本帮助
|
||||
USAGE
|
||||
else
|
||||
cat <<'USAGE'
|
||||
Usage: ./install.sh [options]
|
||||
|
||||
Options:
|
||||
--docker Deploy with Docker (docker-compose.yml)
|
||||
--tag <TAG> Target image tag (e.g. v0.3.34 / latest)
|
||||
--local Build and run locally with Go
|
||||
--skip-pull Skip pulling images (for locally built images)
|
||||
-y, --yes Non-interactive mode (use default values)
|
||||
-h, --help Show this help
|
||||
USAGE
|
||||
fi
|
||||
}
|
||||
|
||||
OPT_DOCKER=0
|
||||
@@ -137,12 +156,12 @@ OPT_LOCAL=0
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--docker) OPT_DOCKER=1 ;;
|
||||
--tag) shift; [ "$#" -gt 0 ] || die "--tag 需要参数"; OPT_TAG="$1" ;;
|
||||
--tag) shift; [ "$#" -gt 0 ] || die_l "--tag 需要参数" "--tag requires a value"; OPT_TAG="$1" ;;
|
||||
--local) OPT_LOCAL=1 ;;
|
||||
--skip-pull) export ARTEX_SKIP_PULL=1 ;;
|
||||
-y|--yes) export ARTEX_NONINTERACTIVE=1 ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
*) die "未知参数:$1(使用 --help 查看帮助)" ;;
|
||||
*) die_l "未知参数:$1(使用 --help 查看帮助)" "Unknown option: $1 (use --help for usage)" ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
@@ -158,12 +177,12 @@ if [ "$OPT_DOCKER" -eq 1 ]; then
|
||||
fi
|
||||
|
||||
echo "=========================================="
|
||||
echo " ARTEX 安装部署"
|
||||
echo " 1) Docker 部署(推荐:独立沙箱 + 全流量网关)"
|
||||
echo " 2) 本地运行(Go 编译)"
|
||||
echo "$(msg ' ARTEX 安装部署' ' ARTEX Installer')"
|
||||
echo "$(msg ' 1) Docker 部署(推荐:独立沙箱 + 全流量网关)' ' 1) Docker deployment (recommended: isolated sandbox + transparent gateway)')"
|
||||
echo "$(msg ' 2) 本地运行(Go 编译)' ' 2) Local run (build with Go)')"
|
||||
echo "=========================================="
|
||||
case "$(ask '选择' 1)" in
|
||||
case "$(ask_l '选择' 'Select' 1)" in
|
||||
1) install_docker "$OPT_TAG" ;;
|
||||
2) install_local ;;
|
||||
*) die "无效选择" ;;
|
||||
*) die_l "无效选择" "Invalid selection" ;;
|
||||
esac
|
||||
+65
-23
@@ -37,11 +37,51 @@ EXEC_KIND="" # compose | docker(docker 模式下用哪种 exec;空=自
|
||||
NEWPASS=""
|
||||
ASSUME_YES=0
|
||||
|
||||
die() { echo "错误:$*" >&2; exit 1; }
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
if [ -f "${SCRIPT_DIR}/scripts/deploy-lib.sh" ]; then
|
||||
# shellcheck source=scripts/deploy-lib.sh
|
||||
. "${SCRIPT_DIR}/scripts/deploy-lib.sh"
|
||||
else
|
||||
ARTEX_SCRIPT_LANG="en"
|
||||
case "$(printf '%s' "${ARTEX_LANG:-${TZ:-}}" | tr '[:upper:]' '[:lower:]')" in
|
||||
zh*|*shanghai*|*chongqing*|*urumqi*|*hong_kong*|*macau*|*taipei*|prc|roc|cst-8*) ARTEX_SCRIPT_LANG="zh" ;;
|
||||
esac
|
||||
msg() { if [ "$ARTEX_SCRIPT_LANG" = "zh" ]; then printf '%s' "$1"; else printf '%s' "$2"; fi; }
|
||||
fi
|
||||
|
||||
die() { echo "$(msg "错误:$*" "Error: $*")" >&2; exit 1; }
|
||||
info() { echo "· $*" >&2; }
|
||||
die_l() { die "$(msg "$1" "$2")"; }
|
||||
info_l() { info "$(msg "$1" "$2")"; }
|
||||
|
||||
usage() { sed -n '2,40p' "$0" | sed 's/^# \{0,1\}//'; exit 0; }
|
||||
usage() {
|
||||
if [ "$ARTEX_SCRIPT_LANG" = "zh" ]; then
|
||||
sed -n '2,25p' "$0" | sed 's/^# \{0,1\}//'
|
||||
else
|
||||
cat <<'USAGE'
|
||||
=============================================================================
|
||||
ARTEX Admin Password Reset Script
|
||||
|
||||
The login username is always ARTEX; the password is stored as a bcrypt hash
|
||||
under settings key auth.password_hash. This script uses PostgreSQL pgcrypto
|
||||
to generate a bcrypt hash compatible with golang.org/x/crypto/bcrypt.
|
||||
|
||||
Modes:
|
||||
local (default) -- Connect via local psql (CLI args > --dsn/$ARTEX_PG_DSN > config.json)
|
||||
docker -- Run psql inside the postgres container via docker compose exec / docker exec
|
||||
|
||||
Examples:
|
||||
./reset-password.sh
|
||||
./reset-password.sh -p 'NewPass!'
|
||||
./reset-password.sh --dsn postgres://u:p@h:5432/artex
|
||||
./reset-password.sh -H 127.0.0.1 -P 5433 -U artex -W pass -d artex
|
||||
./reset-password.sh -m docker
|
||||
./reset-password.sh -m docker -c pg-container --exec docker
|
||||
=============================================================================
|
||||
USAGE
|
||||
fi
|
||||
exit 0
|
||||
}
|
||||
# ---- 参数解析 -------------------------------------------------------------
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
@@ -59,7 +99,7 @@ while [[ $# -gt 0 ]]; do
|
||||
-p|--new-password) NEWPASS="${2:-}"; shift 2 ;;
|
||||
-y|--yes) ASSUME_YES=1; shift ;;
|
||||
-h|--help) usage ;;
|
||||
*) die "未知参数:$1(-h 查看用法)" ;;
|
||||
*) die_l "未知参数:$1(-h 查看用法)" "Unknown option: $1 (-h for usage)" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
@@ -120,16 +160,16 @@ if [[ -z "$MODE" ]]; then
|
||||
MODE="local"
|
||||
fi
|
||||
fi
|
||||
info "部署模式:$MODE"
|
||||
info_l "部署模式:$MODE" "Deployment mode: $MODE"
|
||||
|
||||
# ---- 采集新密码 -----------------------------------------------------------
|
||||
if [[ -z "$NEWPASS" ]]; then
|
||||
read -r -s -p "输入新密码(用户名固定为 ARTEX):" NEWPASS; echo >&2
|
||||
[[ -n "$NEWPASS" ]] || die "密码不能为空"
|
||||
read -r -s -p "再次输入以确认:" NEWPASS2; echo >&2
|
||||
[[ "$NEWPASS" == "$NEWPASS2" ]] || die "两次输入不一致"
|
||||
read -r -s -p "$(msg '输入新密码(用户名固定为 ARTEX):' 'Enter new password (username is ARTEX): ')" NEWPASS; echo >&2
|
||||
[[ -n "$NEWPASS" ]] || die_l "密码不能为空" "Password cannot be empty"
|
||||
read -r -s -p "$(msg '再次输入以确认:' 'Confirm new password: ')" NEWPASS2; echo >&2
|
||||
[[ "$NEWPASS" == "$NEWPASS2" ]] || die_l "两次输入不一致" "Passwords do not match"
|
||||
fi
|
||||
[[ -n "$NEWPASS" ]] || die "密码不能为空"
|
||||
[[ -n "$NEWPASS" ]] || die_l "密码不能为空" "Password cannot be empty"
|
||||
|
||||
# 通过环境变量把密码交给 psql(\getenv 读取,不进入 argv/ps)
|
||||
export ARTEX_RESET_NEWPASS="$NEWPASS"
|
||||
@@ -155,20 +195,20 @@ if [[ "$MODE" == "local" ]]; then
|
||||
if [[ -z "$DSN" && -z "$HOST$USER$DBNAME" ]]; then
|
||||
cfg="${CONFIG:-config.json}"
|
||||
if [[ -f "$cfg" ]]; then
|
||||
info "从 $cfg 读取数据库配置"
|
||||
info_l "从 $cfg 读取数据库配置" "Reading database config from $cfg"
|
||||
apply_config_fields < <(read_config_json "$cfg")
|
||||
fi
|
||||
fi
|
||||
|
||||
command -v psql >/dev/null 2>&1 || die "本机未找到 psql(请安装 postgresql-client,或改用 -m docker)"
|
||||
command -v psql >/dev/null 2>&1 || die_l "本机未找到 psql(请安装 postgresql-client,或改用 -m docker)" "psql not found locally (install postgresql-client or use -m docker)"
|
||||
|
||||
declare -a PSQL_ARGS=()
|
||||
if [[ -n "$DSN" ]]; then
|
||||
PSQL_ARGS=("$DSN")
|
||||
target="$DSN"
|
||||
else
|
||||
[[ -n "$USER" ]] || die "缺少数据库用户(-U)或有效的 config.json/DSN"
|
||||
[[ -n "$DBNAME" ]] || die "缺少数据库名(-d)或有效的 config.json/DSN"
|
||||
[[ -n "$USER" ]] || die_l "缺少数据库用户(-U)或有效的 config.json/DSN" "Missing database user (-U) or valid config.json/DSN"
|
||||
[[ -n "$DBNAME" ]] || die_l "缺少数据库名(-d)或有效的 config.json/DSN" "Missing database name (-d) or valid config.json/DSN"
|
||||
HOST="${HOST:-127.0.0.1}"; PORT="${PORT:-5432}"; SSLMODE="${SSLMODE:-disable}"
|
||||
PSQL_ARGS=(-h "$HOST" -p "$PORT" -U "$USER" -d "$DBNAME")
|
||||
[[ -n "$SSLMODE" ]] && export PGSSLMODE="$SSLMODE"
|
||||
@@ -176,19 +216,20 @@ if [[ "$MODE" == "local" ]]; then
|
||||
target="$USER@$HOST:$PORT/$DBNAME"
|
||||
fi
|
||||
|
||||
info "目标数据库:$target"
|
||||
info_l "目标数据库:$target" "Target database: $target"
|
||||
if [[ "$ASSUME_YES" -ne 1 ]]; then
|
||||
read -r -p "确认在该库重置 ARTEX 密码?[y/N] " ans
|
||||
[[ "$ans" == "y" || "$ans" == "Y" ]] || die "已取消"
|
||||
read -r -p "$(msg '确认在该库重置 ARTEX 密码?[y/N] ' 'Reset ARTEX password in this database? [y/N] ')" ans
|
||||
[[ "$ans" == "y" || "$ans" == "Y" ]] || die_l "已取消" "Cancelled"
|
||||
fi
|
||||
|
||||
if ! printf '%s\n' "$SQL" | psql "${PSQL_ARGS[@]}" -v ON_ERROR_STOP=1 -q >/dev/null; then
|
||||
die "写入失败。若报 pgcrypto 权限/缺失,请用具备建扩展权限的角色,或先手动执行 CREATE EXTENSION pgcrypto。"
|
||||
die_l "写入失败。若报 pgcrypto 权限/缺失,请用具备建扩展权限的角色,或先手动执行 CREATE EXTENSION pgcrypto。" \
|
||||
"Write failed. If pgcrypto is missing or permission was denied, use a role with CREATE EXTENSION privileges or run CREATE EXTENSION pgcrypto first."
|
||||
fi
|
||||
|
||||
else
|
||||
# ---- docker ----
|
||||
command -v docker >/dev/null 2>&1 || die "未找到 docker"
|
||||
command -v docker >/dev/null 2>&1 || die_l "未找到 docker" "docker not found"
|
||||
CONTAINER="${CONTAINER:-postgres}"
|
||||
|
||||
# 选择 exec 方式:优先 docker compose exec(服务名),否则 docker exec(容器名)
|
||||
@@ -210,10 +251,10 @@ else
|
||||
[[ -n "$DBPASS" ]] && export PGPASSWORD="$DBPASS"
|
||||
[[ -z "${PGPASSWORD:-}" && -n "${POSTGRES_PASSWORD:-}" ]] && export PGPASSWORD="$POSTGRES_PASSWORD"
|
||||
|
||||
info "目标:容器 $CONTAINER 内 psql -U $DUSER -d $DNAME(exec=$EXEC_KIND)"
|
||||
info_l "目标:容器 $CONTAINER 内 psql -U $DUSER -d $DNAME(exec=$EXEC_KIND)" "Target: psql -U $DUSER -d $DNAME inside container $CONTAINER (exec=$EXEC_KIND)"
|
||||
if [[ "$ASSUME_YES" -ne 1 ]]; then
|
||||
read -r -p "确认在该容器数据库重置 ARTEX 密码?[y/N] " ans
|
||||
[[ "$ans" == "y" || "$ans" == "Y" ]] || die "已取消"
|
||||
read -r -p "$(msg '确认在该容器数据库重置 ARTEX 密码?[y/N] ' 'Reset ARTEX password in this container database? [y/N] ')" ans
|
||||
[[ "$ans" == "y" || "$ans" == "Y" ]] || die_l "已取消" "Cancelled"
|
||||
fi
|
||||
|
||||
# -e 只带名字不带值 → 从当前环境继承,密码不出现在 docker 命令 argv 里。
|
||||
@@ -227,9 +268,10 @@ else
|
||||
fi
|
||||
|
||||
if ! printf '%s\n' "$SQL" | "${EXEC_CMD[@]}" >/dev/null; then
|
||||
die "写入失败。请确认容器名(-c)、数据库账号(.env 的 POSTGRES_*),以及角色有 pgcrypto 权限。"
|
||||
die_l "写入失败。请确认容器名(-c)、数据库账号(.env 的 POSTGRES_*),以及角色有 pgcrypto 权限。" \
|
||||
"Write failed. Verify the container name (-c), database credentials (.env POSTGRES_*), and pgcrypto extension privileges."
|
||||
fi
|
||||
fi
|
||||
|
||||
unset ARTEX_RESET_NEWPASS
|
||||
echo "✓ 已重置 ARTEX 管理员密码。请用用户名 ARTEX + 新密码登录(无需重启服务)。"
|
||||
echo "$(msg '✓ 已重置 ARTEX 管理员密码。请用用户名 ARTEX + 新密码登录(无需重启服务)。' '✓ ARTEX admin password reset. Log in with username ARTEX and the new password (no restart needed).')"
|
||||
+152
-38
@@ -9,10 +9,75 @@ COMPOSE_FILE="${ARTEX_COMPOSE_FILE:-docker-compose.yml}"
|
||||
HEALTH_CHECK_URL="${ARTEX_HEALTH_URL:-http://127.0.0.1:8787/api/health}"
|
||||
HEALTH_CHECK_TIMEOUT="${ARTEX_HEALTH_TIMEOUT:-60}"
|
||||
|
||||
# ── 按系统时区自动选择脚本语言(zh / en;支持 ARTEX_LANG 显式覆盖)─────
|
||||
detect_system_timezone(){
|
||||
local tz=""
|
||||
if [ -n "${TZ:-}" ]; then
|
||||
tz="${TZ#:}"
|
||||
elif [ -r /etc/timezone ]; then
|
||||
tz="$(tr -d ' \t\r\n' < /etc/timezone 2>/dev/null || true)"
|
||||
fi
|
||||
if [ -z "$tz" ] && [ -L /etc/localtime ]; then
|
||||
tz="$(readlink /etc/localtime 2>/dev/null || true)"
|
||||
fi
|
||||
if [ -z "$tz" ] && command -v timedatectl >/dev/null 2>&1; then
|
||||
tz="$(timedatectl show -p Timezone --value 2>/dev/null || true)"
|
||||
fi
|
||||
case "$tz" in
|
||||
*zoneinfo/*) tz="${tz#*zoneinfo/}" ;;
|
||||
esac
|
||||
printf '%s\n' "$tz"
|
||||
}
|
||||
|
||||
detect_script_lang(){
|
||||
local override
|
||||
override="$(printf '%s' "${ARTEX_LANG:-}" | tr '[:upper:]' '[:lower:]')"
|
||||
case "$override" in
|
||||
zh|zh_*|zh-*) printf 'zh\n'; return 0 ;;
|
||||
en|en_*|en-*) printf 'en\n'; return 0 ;;
|
||||
esac
|
||||
|
||||
local tz tz_lc
|
||||
tz="$(detect_system_timezone)"
|
||||
tz_lc="$(printf '%s' "$tz" | tr '[:upper:]' '[:lower:]')"
|
||||
case "$tz_lc" in
|
||||
asia/shanghai|asia/chongqing|asia/chungking|asia/harbin|asia/kashgar|asia/urumqi|\
|
||||
asia/hong_kong|asia/macau|asia/macao|asia/taipei|\
|
||||
prc|roc|hongkong|etc/gmt-8|cst-8|cst-8:*|hkt|hkt-8*)
|
||||
printf 'zh\n'
|
||||
return 0
|
||||
;;
|
||||
"")
|
||||
local abbr offset
|
||||
abbr="$(date +%Z 2>/dev/null || true)"
|
||||
offset="$(date +%z 2>/dev/null || true)"
|
||||
if { [ "$abbr" = "CST" ] && [ "$offset" = "+0800" ]; } || [ "$abbr" = "HKT" ]; then
|
||||
printf 'zh\n'
|
||||
return 0
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
printf 'en\n'
|
||||
}
|
||||
|
||||
ARTEX_SCRIPT_LANG="$(detect_script_lang)"
|
||||
|
||||
msg(){
|
||||
if [ "$ARTEX_SCRIPT_LANG" = "zh" ]; then
|
||||
printf '%s' "$1"
|
||||
else
|
||||
printf '%s' "$2"
|
||||
fi
|
||||
}
|
||||
|
||||
info(){ printf '\033[36m[*]\033[0m %s\n' "$*"; }
|
||||
ok(){ printf '\033[32m[+]\033[0m %s\n' "$*"; }
|
||||
warn(){ printf '\033[33m[!]\033[0m %s\n' "$*" >&2; }
|
||||
die(){ printf '\033[31m[x]\033[0m %s\n' "$*" >&2; exit 1; }
|
||||
info_l(){ info "$(msg "$1" "$2")"; }
|
||||
ok_l(){ ok "$(msg "$1" "$2")"; }
|
||||
warn_l(){ warn "$(msg "$1" "$2")"; }
|
||||
die_l(){ die "$(msg "$1" "$2")"; }
|
||||
ask(){
|
||||
local p="$1" d="${2:-}" a=""
|
||||
if [ "${ARTEX_NONINTERACTIVE:-0}" = "1" ]; then
|
||||
@@ -22,6 +87,15 @@ ask(){
|
||||
read -rp "$p${d:+ [$d]}: " a
|
||||
echo "${a:-$d}"
|
||||
}
|
||||
ask_l(){
|
||||
ask "$(msg "$1" "$2")" "${3:-}"
|
||||
}
|
||||
is_yes(){
|
||||
case "${1:-}" in
|
||||
y|Y|yes|YES) return 0 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
rand(){
|
||||
local n="${1:-24}"
|
||||
LC_ALL=C tr -dc 'A-Za-z0-9' </dev/urandom | head -c "$n"
|
||||
@@ -124,7 +198,7 @@ init_base_env(){
|
||||
cur_pw="$(env_get POSTGRES_PASSWORD "$file")"
|
||||
if [ -z "$cur_pw" ] || [ "$cur_pw" = "change-me-please" ]; then
|
||||
local pw
|
||||
pw="$(ask 'Postgres 密码(回车随机生成)' "$(rand 24)")"
|
||||
pw="$(ask_l 'Postgres 密码(回车随机生成)' 'Postgres password (Enter to auto-generate)' "$(rand 24)")"
|
||||
env_set POSTGRES_PASSWORD "$pw" "$file"
|
||||
fi
|
||||
mkdir -p ./data ./skills
|
||||
@@ -186,21 +260,21 @@ prepare_env_for_docker(){
|
||||
abs_data="$(pwd)/data"
|
||||
if [ -z "$cur_data" ] || [ "$cur_data" = "/path/to/ARTEX/data" ]; then
|
||||
env_set ARTEX_HOST_DATA_DIR "$abs_data" "$file"
|
||||
ok "已设置 ARTEX_HOST_DATA_DIR=${abs_data}"
|
||||
ok_l "已设置 ARTEX_HOST_DATA_DIR=${abs_data}" "Set ARTEX_HOST_DATA_DIR=${abs_data}"
|
||||
fi
|
||||
|
||||
local cur_tok
|
||||
cur_tok="$(env_get ARTEX_GATEWAY_TOKEN "$file")"
|
||||
if [ -z "$cur_tok" ]; then
|
||||
env_set ARTEX_GATEWAY_TOKEN "$(rand 32)" "$file"
|
||||
ok "已自动生成 ARTEX_GATEWAY_TOKEN"
|
||||
ok_l "已自动生成 ARTEX_GATEWAY_TOKEN" "Auto-generated ARTEX_GATEWAY_TOKEN"
|
||||
fi
|
||||
|
||||
if [ -n "$tag" ]; then
|
||||
local norm
|
||||
norm="$(normalize_tag "$tag")"
|
||||
env_set ARTEX_TAG "$norm" "$file"
|
||||
ok "已将 ARTEX_TAG 设为 ${norm}"
|
||||
ok_l "已将 ARTEX_TAG 设为 ${norm}" "Set ARTEX_TAG=${norm}"
|
||||
else
|
||||
local cur_tag
|
||||
cur_tag="$(env_get ARTEX_TAG "$file")"
|
||||
@@ -221,7 +295,7 @@ prepare_migrated_workspaces(){
|
||||
fi
|
||||
for d in "${data_dir}/tasks" "${data_dir}/sessions" "${data_dir}/ephemeral"; do
|
||||
[ -d "$d" ] || continue
|
||||
info "校准迁移目录写权限(跳过符号链接):${d}"
|
||||
info_l "校准迁移目录写权限(跳过符号链接):${d}" "Fixing migrated workspace permissions (skipping symlinks): ${d}"
|
||||
if [ "$use_sudo" -eq 1 ]; then
|
||||
sudo find "$d" ! -type l -type d -exec chmod 0777 {} + 2>/dev/null || true
|
||||
sudo find "$d" ! -type l -type f -exec chmod a+rw {} + 2>/dev/null || true
|
||||
@@ -241,14 +315,37 @@ preflight_docker(){
|
||||
local os_name
|
||||
os_name="$(uname -s)"
|
||||
if [ "$os_name" != "Linux" ]; then
|
||||
warn "检测到当前宿主机为 ${os_name}(非 Linux)。透明网关(artex-gateway)需要 Linux 宿主机网络栈与 /dev/net/tun。"
|
||||
warn_l "检测到当前宿主机为 ${os_name}(非 Linux)。透明网关(artex-gateway)需要 Linux 宿主机网络栈与 /dev/net/tun。" \
|
||||
"Detected host OS ${os_name} (non-Linux). The transparent gateway (artex-gateway) requires Linux host networking and /dev/net/tun."
|
||||
if [ "${ARTEX_NONINTERACTIVE:-0}" != "1" ]; then
|
||||
[ "$(ask '仍继续部署? (y/n)' n)" = "y" ] || die "已取消部署"
|
||||
is_yes "$(ask_l '仍继续部署? (y/n)' 'Continue deployment anyway? (y/n)' n)" || die_l "已取消部署" "Deployment cancelled"
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
if [ ! -e /dev/net/tun ]; then
|
||||
warn "宿主机未发现 /dev/net/tun:artex-gateway 启动时可能无法开启 TUN 模式(请确认内核加载 tun 模块)。"
|
||||
warn_l "宿主机未发现 /dev/net/tun:artex-gateway 启动时可能无法开启 TUN 模式(请确认内核加载 tun 模块)。" \
|
||||
"/dev/net/tun not found on host: artex-gateway may not enable TUN mode (ensure the tun kernel module is loaded)."
|
||||
fi
|
||||
}
|
||||
|
||||
# 校验 docker-compose.yml 是否为新版沙箱隔离拓扑(防止误用旧版 2 服务编排导致静默回退本地模式)
|
||||
validate_sandbox_compose(){
|
||||
local file="${1:-$COMPOSE_FILE}" tag_hint="${2:-main}"
|
||||
[ -n "$tag_hint" ] && [ "$tag_hint" != "latest" ] || tag_hint="main"
|
||||
if [ ! -f "$file" ]; then
|
||||
die_l "未找到编排文件:${file}。请先同步最新 docker-compose.yml 后重试。" \
|
||||
"Compose file not found: ${file}. Sync the latest docker-compose.yml first."
|
||||
fi
|
||||
if ! grep -Eq '^[[:space:]]*docker-socket-proxy:[[:space:]]*$' "$file" \
|
||||
|| ! grep -Eq '^[[:space:]]*artex-gateway:[[:space:]]*$' "$file" \
|
||||
|| ! grep -Eq 'ARTEX_SANDBOX_MODE' "$file"; then
|
||||
warn_l "检测到当前 ${file} 为旧版单容器编排(缺少 docker-socket-proxy / artex-gateway / ARTEX_SANDBOX_MODE),继续执行会导致升级后仍停留在本地模式。" \
|
||||
"Detected legacy single-container ${file} (missing docker-socket-proxy / artex-gateway / ARTEX_SANDBOX_MODE); continuing would leave ARTEX in local mode."
|
||||
warn_l "请先更新 ${file} 再重试(git 部署请先执行 git pull --ff-only;非 git 部署可执行):" \
|
||||
"Update ${file} first and retry (run 'git pull --ff-only' for git clones, or for non-git deployments run):"
|
||||
printf ' cp %s %s.bak && curl -fsSL https://raw.githubusercontent.com/RuoJi6/ARTEX/%s/docker-compose.yml -o %s\n' \
|
||||
"$file" "$file" "$tag_hint" "$file" >&2
|
||||
die_l "已中止升级,避免误用旧版编排文件。" "Aborted to prevent running with an outdated compose file."
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -258,7 +355,7 @@ stop_sandbox_runtime(){
|
||||
if command -v docker >/dev/null 2>&1; then
|
||||
sbx_cids="$(docker ps -q --filter "label=artex.sandbox.managed=true" 2>/dev/null || true)"
|
||||
if [ -n "$sbx_cids" ]; then
|
||||
info "停止运行中的沙箱任务/会话容器…"
|
||||
info_l "停止运行中的沙箱任务/会话容器…" "Stopping running sandbox task/session containers..."
|
||||
# shellcheck disable=SC2086
|
||||
docker stop -t 10 $sbx_cids >/dev/null 2>&1 || true
|
||||
fi
|
||||
@@ -266,7 +363,8 @@ stop_sandbox_runtime(){
|
||||
local gw_cid
|
||||
gw_cid="$(find_service_cid artex-gateway "$COMPOSE_FILE")"
|
||||
if [ -n "$gw_cid" ]; then
|
||||
info "优雅停止透明代理网关 artex-gateway(自动清理 TUN 与 iptables 规则)…"
|
||||
info_l "优雅停止透明代理网关 artex-gateway(自动清理 TUN 与 iptables 规则)…" \
|
||||
"Gracefully stopping transparent gateway artex-gateway (cleaning up TUN & iptables rules)..."
|
||||
docker compose -f "$COMPOSE_FILE" stop -t 15 artex-gateway >/dev/null 2>&1 || true
|
||||
fi
|
||||
fi
|
||||
@@ -279,7 +377,8 @@ stop_sandbox_runtime(){
|
||||
elif command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then
|
||||
sudo ./scripts/artex-sandbox-firewall.sh --cleanup >/dev/null 2>&1 || true
|
||||
elif command -v ip >/dev/null 2>&1 && ip link show artex-tun0 >/dev/null 2>&1; then
|
||||
warn "检测到宿主机残留 artex-tun0 / 策略路由,如需清理请执行:sudo ./scripts/artex-sandbox-firewall.sh --cleanup"
|
||||
warn_l "检测到宿主机残留 artex-tun0 / 策略路由,如需清理请执行:sudo ./scripts/artex-sandbox-firewall.sh --cleanup" \
|
||||
"Residual artex-tun0 / policy routing detected on host; to clean up run: sudo ./scripts/artex-sandbox-firewall.sh --cleanup"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
@@ -291,24 +390,24 @@ wait_for_health(){
|
||||
if [ "${ARTEX_SKIP_HEALTH:-0}" = "1" ]; then
|
||||
return 0
|
||||
fi
|
||||
info "等待服务就绪(${url},超时 ${timeout_s}s)…"
|
||||
info_l "等待服务就绪(${url},超时 ${timeout_s}s)…" "Waiting for service readiness (${url}, timeout ${timeout_s}s)..."
|
||||
while [ "$elapsed" -lt "$timeout_s" ]; do
|
||||
if command -v curl >/dev/null 2>&1 && curl -fsS --max-time 3 "$url" >/dev/null 2>&1; then
|
||||
ok "健康检查通过:${url}"
|
||||
ok_l "健康检查通过:${url}" "Health check passed: ${url}"
|
||||
return 0
|
||||
fi
|
||||
cid="$(find_service_cid artex "$compose_file")"
|
||||
if [ -n "$cid" ]; then
|
||||
state="$(docker inspect --format '{{.State.Status}}' "$cid" 2>/dev/null || true)"
|
||||
if [ "$state" = "exited" ] || [ "$state" = "dead" ]; then
|
||||
warn "artex 容器异常退出(state=${state})"
|
||||
warn_l "artex 容器异常退出(state=${state})" "artex container exited unexpectedly (state=${state})"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
sleep 2
|
||||
elapsed=$((elapsed + 2))
|
||||
done
|
||||
warn "等待 ${url} 就绪超时(${timeout_s}s)"
|
||||
warn_l "等待 ${url} 就绪超时(${timeout_s}s)" "Timed out waiting for ${url} (${timeout_s}s)"
|
||||
return 1
|
||||
}
|
||||
|
||||
@@ -354,6 +453,7 @@ create_deploy_snapshot(){
|
||||
mkdir -p "$snap_dir"
|
||||
|
||||
[ -f .env ] && cp .env "${snap_dir}/dot.env"
|
||||
[ -f "$COMPOSE_FILE" ] && cp "$COMPOSE_FILE" "${snap_dir}/docker-compose.yml"
|
||||
|
||||
if command -v docker >/dev/null 2>&1; then
|
||||
artex_cid="$(find_service_cid artex)"
|
||||
@@ -423,7 +523,7 @@ META
|
||||
|
||||
list_deploy_snapshots(){
|
||||
if [ ! -d "$DEPLOY_SNAP_DIR" ]; then
|
||||
info "暂无部署快照(升级前会自动生成)"
|
||||
info_l "暂无部署快照(升级前会自动生成)" "No deployment snapshots found (created automatically before upgrades)"
|
||||
return 0
|
||||
fi
|
||||
local found=0 dir snap_id img pg reason
|
||||
@@ -434,11 +534,16 @@ list_deploy_snapshots(){
|
||||
img="$(env_get ARTEX_IMAGE_REF "${dir}/meta.env")"
|
||||
pg="$(env_get HAS_PG_DUMP "${dir}/meta.env")"
|
||||
reason="$(env_get SNAP_REASON "${dir}/meta.env")"
|
||||
printf ' - %s [镜像: %s] [DB备份: %s] [来源: %s]\n' \
|
||||
"$snap_id" "${img:-unknown}" "$([ "$pg" = "1" ] && echo "有" || echo "无")" "${reason:-?}"
|
||||
if [ "$ARTEX_SCRIPT_LANG" = "zh" ]; then
|
||||
printf ' - %s [镜像: %s] [DB备份: %s] [来源: %s]\n' \
|
||||
"$snap_id" "${img:-unknown}" "$([ "$pg" = "1" ] && echo "有" || echo "无")" "${reason:-?}"
|
||||
else
|
||||
printf ' - %s [image: %s] [DB backup: %s] [reason: %s]\n' \
|
||||
"$snap_id" "${img:-unknown}" "$([ "$pg" = "1" ] && echo "yes" || echo "no")" "${reason:-?}"
|
||||
fi
|
||||
done
|
||||
if [ "$found" -eq 0 ]; then
|
||||
info "暂无部署快照"
|
||||
info_l "暂无部署快照" "No deployment snapshots found"
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -478,7 +583,8 @@ restore_snapshot_images(){
|
||||
fi
|
||||
env_set ARTEX_IMAGE "${artex_rb%:*}" .env
|
||||
env_set ARTEX_TAG "${artex_rb##*:}" .env
|
||||
ok "已绑定本地精确回滚镜像:${artex_rb}(原镜像:${artex_ref:-unknown})"
|
||||
ok_l "已绑定本地精确回滚镜像:${artex_rb}(原镜像:${artex_ref:-unknown})" \
|
||||
"Pinned local rollback image: ${artex_rb} (original: ${artex_ref:-unknown})"
|
||||
elif [ -n "$artex_ref" ]; then
|
||||
local repo="${artex_ref%:*}" tag="${artex_ref##*:}"
|
||||
if [ "$repo" != "$artex_ref" ] && [ -n "$tag" ]; then
|
||||
@@ -516,34 +622,36 @@ restore_snapshot_images(){
|
||||
|
||||
restore_postgres_dump(){
|
||||
local dump_gz="$1" compose_file="$2"
|
||||
[ -f "$dump_gz" ] || die "快照中不存在数据库备份:${dump_gz}"
|
||||
[ -f "$dump_gz" ] || die_l "快照中不存在数据库备份:${dump_gz}" "Database backup not found in snapshot: ${dump_gz}"
|
||||
local pg_cid pg_user pg_db
|
||||
pg_cid="$(find_service_cid postgres "$compose_file")"
|
||||
[ -n "$pg_cid" ] || die "未找到运行中的 postgres 容器,无法恢复数据库备份"
|
||||
[ -n "$pg_cid" ] || die_l "未找到运行中的 postgres 容器,无法恢复数据库备份" "No running postgres container found; cannot restore database backup"
|
||||
pg_user="$(env_get POSTGRES_USER .env)"; [ -n "$pg_user" ] || pg_user="artex"
|
||||
pg_db="$(env_get POSTGRES_DB .env)"; [ -n "$pg_db" ] || pg_db="artex"
|
||||
|
||||
info "停止 artex 并恢复 PostgreSQL 快照(${dump_gz})…"
|
||||
info_l "停止 artex 并恢复 PostgreSQL 快照(${dump_gz})…" "Stopping artex and restoring PostgreSQL snapshot (${dump_gz})..."
|
||||
docker compose -f "$compose_file" stop artex >/dev/null 2>&1 || true
|
||||
docker exec "$pg_cid" psql -U "$pg_user" -d postgres -v ON_ERROR_STOP=1 \
|
||||
-c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${pg_db}' AND pid <> pg_backend_pid();" >/dev/null 2>&1 || true
|
||||
docker exec "$pg_cid" psql -U "$pg_user" -d "$pg_db" -v ON_ERROR_STOP=1 \
|
||||
-c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;" >/dev/null
|
||||
gzip -dc "$dump_gz" | docker exec -i "$pg_cid" psql -U "$pg_user" -d "$pg_db" -v ON_ERROR_STOP=1 >/dev/null
|
||||
ok "PostgreSQL 快照恢复完成"
|
||||
ok_l "PostgreSQL 快照恢复完成" "PostgreSQL snapshot restored"
|
||||
}
|
||||
|
||||
rollback_to_snapshot(){
|
||||
local snap_id="${1:-}" restore_db="${2:-0}"
|
||||
if [ -z "$snap_id" ]; then
|
||||
[ -f "${DEPLOY_STATE_DIR}/latest" ] || die "未找到可回滚的部署快照(${DEPLOY_STATE_DIR}/latest 不存在)"
|
||||
[ -f "${DEPLOY_STATE_DIR}/latest" ] || die_l "未找到可回滚的部署快照(${DEPLOY_STATE_DIR}/latest 不存在)" \
|
||||
"No rollback snapshot found (${DEPLOY_STATE_DIR}/latest does not exist)"
|
||||
snap_id="$(cat "${DEPLOY_STATE_DIR}/latest")"
|
||||
fi
|
||||
local snap_dir="${DEPLOY_SNAP_DIR}/${snap_id}"
|
||||
local meta="${snap_dir}/meta.env"
|
||||
[ -f "$meta" ] || die "快照不存在:${snap_id}(可用 ./update.sh --list-snapshots 查看)"
|
||||
[ -f "$meta" ] || die_l "快照不存在:${snap_id}(可用 ./update.sh --list-snapshots 查看)" \
|
||||
"Snapshot not found: ${snap_id} (run ./update.sh --list-snapshots to list snapshots)"
|
||||
|
||||
info "开始回滚到快照 ${snap_id}…"
|
||||
info_l "开始回滚到快照 ${snap_id}…" "Rolling back to snapshot ${snap_id}..."
|
||||
|
||||
stop_sandbox_runtime
|
||||
|
||||
@@ -554,6 +662,9 @@ rollback_to_snapshot(){
|
||||
cp "${snap_dir}/dot.env" .env
|
||||
chmod 600 .env 2>/dev/null || true
|
||||
fi
|
||||
if [ -f "${snap_dir}/docker-compose.yml" ]; then
|
||||
cp "${snap_dir}/docker-compose.yml" "$COMPOSE_FILE"
|
||||
fi
|
||||
|
||||
env_set ARTEX_SANDBOX_MODE "docker" .env
|
||||
restore_snapshot_images "$meta"
|
||||
@@ -563,13 +674,14 @@ rollback_to_snapshot(){
|
||||
restore_postgres_dump "${snap_dir}/postgres.sql.gz" "$COMPOSE_FILE"
|
||||
fi
|
||||
|
||||
info "启动服务(${COMPOSE_FILE} --remove-orphans)…"
|
||||
info_l "启动服务(${COMPOSE_FILE} --remove-orphans)…" "Starting services (${COMPOSE_FILE} --remove-orphans)..."
|
||||
docker compose -f "$COMPOSE_FILE" up -d --remove-orphans
|
||||
|
||||
if wait_for_health "$COMPOSE_FILE"; then
|
||||
ok "回滚完成 → http://localhost:8787"
|
||||
ok_l "回滚完成 → http://localhost:8787" "Rollback complete -> http://localhost:8787"
|
||||
else
|
||||
die "回滚后健康检查未通过,请执行 docker compose -f ${COMPOSE_FILE} logs --tail=80 artex 排查"
|
||||
die_l "回滚后健康检查未通过,请执行 docker compose -f ${COMPOSE_FILE} logs --tail=80 artex 排查" \
|
||||
"Health check failed after rollback; check logs: docker compose -f ${COMPOSE_FILE} logs --tail=80 artex"
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -577,14 +689,15 @@ rollback_to_snapshot(){
|
||||
pull_docker_images(){
|
||||
local sbx_img
|
||||
if [ "${ARTEX_SKIP_PULL:-0}" = "1" ]; then
|
||||
info "已跳过镜像拉取(ARTEX_SKIP_PULL=1)"
|
||||
info_l "已跳过镜像拉取(ARTEX_SKIP_PULL=1)" "Skipped image pull (ARTEX_SKIP_PULL=1)"
|
||||
return 0
|
||||
fi
|
||||
info "拉取镜像(artex / artex-gateway / docker-socket-proxy / postgres)…"
|
||||
info_l "拉取镜像(artex / artex-gateway / docker-socket-proxy / postgres)…" \
|
||||
"Pulling images (artex / artex-gateway / docker-socket-proxy / postgres)..."
|
||||
docker compose -f "$COMPOSE_FILE" pull
|
||||
sbx_img="$(env_get ARTEX_SANDBOX_IMAGE .env)"
|
||||
[ -n "$sbx_img" ] || sbx_img="ruoji6/artex-sandbox:latest"
|
||||
info "拉取沙箱执行镜像(${sbx_img})…"
|
||||
info_l "拉取沙箱执行镜像(${sbx_img})…" "Pulling sandbox worker image (${sbx_img})..."
|
||||
docker pull "$sbx_img"
|
||||
}
|
||||
|
||||
@@ -592,14 +705,15 @@ deploy_with_rollback(){
|
||||
local snap_id="${1:-}"
|
||||
|
||||
pull_docker_images
|
||||
info "启动服务(${COMPOSE_FILE})…"
|
||||
info_l "启动服务(${COMPOSE_FILE})…" "Starting services (${COMPOSE_FILE})..."
|
||||
if ! docker compose -f "$COMPOSE_FILE" up -d --remove-orphans || ! wait_for_health "$COMPOSE_FILE"; then
|
||||
warn "新版本启动或健康检查失败!"
|
||||
warn_l "新版本启动或健康检查失败!" "New version failed to start or pass health check!"
|
||||
if [ -n "$snap_id" ] && [ -f "${DEPLOY_SNAP_DIR}/${snap_id}/meta.env" ]; then
|
||||
warn "正在自动回滚到操作前快照 ${snap_id}…"
|
||||
warn_l "正在自动回滚到操作前快照 ${snap_id}…" "Automatically rolling back to pre-upgrade snapshot ${snap_id}..."
|
||||
rollback_to_snapshot "$snap_id" 0
|
||||
die "已自动回滚到 ${snap_id},请排查失败原因后重试"
|
||||
die_l "已自动回滚到 ${snap_id},请排查失败原因后重试" "Automatically rolled back to ${snap_id}; investigate the failure and retry"
|
||||
fi
|
||||
die "启动失败,请查看日志:docker compose -f ${COMPOSE_FILE} logs --tail=80 artex"
|
||||
die_l "启动失败,请查看日志:docker compose -f ${COMPOSE_FILE} logs --tail=80 artex" \
|
||||
"Startup failed; check logs: docker compose -f ${COMPOSE_FILE} logs --tail=80 artex"
|
||||
fi
|
||||
}
|
||||
+84
-1
@@ -19,10 +19,14 @@ assert_contains() {
|
||||
grep -Fq -- "$needle" "$file" || fail "${msg}: '${needle}' not found in ${file}"
|
||||
}
|
||||
|
||||
# 1. Syntax check all deployment scripts
|
||||
# 1. Syntax check all shell scripts
|
||||
bash -n "$REPO_ROOT/scripts/deploy-lib.sh"
|
||||
bash -n "$REPO_ROOT/install.sh"
|
||||
bash -n "$REPO_ROOT/update.sh"
|
||||
bash -n "$REPO_ROOT/build.sh"
|
||||
bash -n "$REPO_ROOT/dev.sh"
|
||||
bash -n "$REPO_ROOT/reset-password.sh"
|
||||
sh -n "$REPO_ROOT/start.sh"
|
||||
sh -n "$REPO_ROOT/scripts/artex-sandbox-firewall.sh"
|
||||
pass "shell syntax checks"
|
||||
|
||||
@@ -44,6 +48,56 @@ pass "shell syntax checks"
|
||||
)
|
||||
pass "tag normalization and env helpers"
|
||||
|
||||
# 2b. Unit-test timezone-based language detection & script output switching
|
||||
(
|
||||
# shellcheck source=scripts/deploy-lib.sh
|
||||
. "$REPO_ROOT/scripts/deploy-lib.sh"
|
||||
assert_eq "$(ARTEX_LANG= TZ=Asia/Shanghai detect_script_lang)" "zh" "Asia/Shanghai -> zh"
|
||||
assert_eq "$(ARTEX_LANG= TZ=:Asia/Hong_Kong detect_script_lang)" "zh" ":Asia/Hong_Kong -> zh"
|
||||
assert_eq "$(ARTEX_LANG= TZ=Asia/Taipei detect_script_lang)" "zh" "Asia/Taipei -> zh"
|
||||
assert_eq "$(ARTEX_LANG= TZ=Asia/Macau detect_script_lang)" "zh" "Asia/Macau -> zh"
|
||||
assert_eq "$(ARTEX_LANG= TZ=Asia/Urumqi detect_script_lang)" "zh" "Asia/Urumqi -> zh"
|
||||
assert_eq "$(ARTEX_LANG= TZ=CST-8 detect_script_lang)" "zh" "CST-8 -> zh"
|
||||
assert_eq "$(ARTEX_LANG= TZ=UTC detect_script_lang)" "en" "UTC -> en"
|
||||
assert_eq "$(ARTEX_LANG= TZ=America/New_York detect_script_lang)" "en" "America/New_York -> en"
|
||||
assert_eq "$(ARTEX_LANG= TZ=Europe/London detect_script_lang)" "en" "Europe/London -> en"
|
||||
assert_eq "$(ARTEX_LANG= TZ=Asia/Tokyo detect_script_lang)" "en" "Asia/Tokyo -> en"
|
||||
assert_eq "$(ARTEX_LANG= TZ=Asia/Singapore detect_script_lang)" "en" "Asia/Singapore -> en"
|
||||
assert_eq "$(ARTEX_LANG= TZ=CST6CDT detect_script_lang)" "en" "US CST6CDT -> en"
|
||||
assert_eq "$(ARTEX_LANG=en TZ=Asia/Shanghai detect_script_lang)" "en" "ARTEX_LANG=en overrides zh timezone"
|
||||
assert_eq "$(ARTEX_LANG=zh TZ=UTC detect_script_lang)" "zh" "ARTEX_LANG=zh overrides en timezone"
|
||||
|
||||
# Verify script CLI help switches language by TZ
|
||||
ARTEX_LANG= TZ=Asia/Shanghai "$REPO_ROOT/update.sh" --help > "$TMP_DIR/update-zh.out"
|
||||
ARTEX_LANG= TZ=America/New_York "$REPO_ROOT/update.sh" --help > "$TMP_DIR/update-en.out"
|
||||
assert_contains "$TMP_DIR/update-zh.out" "用法: ./update.sh" "update.sh --help outputs zh for Asia/Shanghai"
|
||||
assert_contains "$TMP_DIR/update-en.out" "Usage: ./update.sh" "update.sh --help outputs en for America/New_York"
|
||||
|
||||
ARTEX_LANG= TZ=Asia/Shanghai "$REPO_ROOT/install.sh" --help > "$TMP_DIR/install-zh.out"
|
||||
ARTEX_LANG= TZ=UTC "$REPO_ROOT/install.sh" --help > "$TMP_DIR/install-en.out"
|
||||
assert_contains "$TMP_DIR/install-zh.out" "用法: ./install.sh" "install.sh --help outputs zh for Asia/Shanghai"
|
||||
assert_contains "$TMP_DIR/install-en.out" "Usage: ./install.sh" "install.sh --help outputs en for UTC"
|
||||
|
||||
ARTEX_LANG= TZ=Asia/Shanghai "$REPO_ROOT/build.sh" --help > "$TMP_DIR/build-zh.out"
|
||||
ARTEX_LANG= TZ=UTC "$REPO_ROOT/build.sh" --help > "$TMP_DIR/build-en.out"
|
||||
assert_contains "$TMP_DIR/build-zh.out" "用法:" "build.sh --help outputs zh for Asia/Shanghai"
|
||||
assert_contains "$TMP_DIR/build-en.out" "Usage:" "build.sh --help outputs en for UTC"
|
||||
|
||||
ARTEX_LANG= TZ=Asia/Shanghai "$REPO_ROOT/reset-password.sh" --help > "$TMP_DIR/reset-zh.out"
|
||||
ARTEX_LANG= TZ=UTC "$REPO_ROOT/reset-password.sh" --help > "$TMP_DIR/reset-en.out"
|
||||
assert_contains "$TMP_DIR/reset-zh.out" "ARTEX 管理员密码重置脚本" "reset-password.sh --help outputs zh for Asia/Shanghai"
|
||||
assert_contains "$TMP_DIR/reset-en.out" "ARTEX Admin Password Reset Script" "reset-password.sh --help outputs en for UTC"
|
||||
|
||||
mkdir -p "$TMP_DIR/start-check"
|
||||
cp "$REPO_ROOT/start.sh" "$TMP_DIR/start-check/start.sh"
|
||||
chmod +x "$TMP_DIR/start-check/start.sh"
|
||||
( ARTEX_LANG= TZ=Asia/Shanghai "$TMP_DIR/start-check/start.sh" 2>"$TMP_DIR/start-zh.err" || true )
|
||||
( ARTEX_LANG= TZ=UTC "$TMP_DIR/start-check/start.sh" 2>"$TMP_DIR/start-en.err" || true )
|
||||
assert_contains "$TMP_DIR/start-zh.err" "找不到可执行文件" "start.sh outputs zh error for Asia/Shanghai"
|
||||
assert_contains "$TMP_DIR/start-en.err" "Executable not found" "start.sh outputs en error for UTC"
|
||||
)
|
||||
pass "timezone-based zh/en language switching"
|
||||
|
||||
# 3. End-to-end workflow test with stubbed docker & curl in isolated workspace
|
||||
WORK="$TMP_DIR/work"
|
||||
BIN_STUB="$TMP_DIR/bin"
|
||||
@@ -258,4 +312,33 @@ assert_eq "$(cd "$FRESH" && . ./scripts/deploy-lib.sh && env_get ARTEX_HOST_DATA
|
||||
[ -n "$(cd "$FRESH" && . ./scripts/deploy-lib.sh && env_get ARTEX_GATEWAY_TOKEN .env)" ] || fail "fresh install sets ARTEX_GATEWAY_TOKEN"
|
||||
pass "fresh install.sh"
|
||||
|
||||
# 3f. Outdated 2-service docker-compose.yml must be rejected (and snapshot backs up compose file)
|
||||
[ -f "$WORK/.artex-deploy/snapshots/$snap_upg/docker-compose.yml" ] || fail "upgrade snapshot did not back up docker-compose.yml"
|
||||
LEGACY_COMPOSE="$TMP_DIR/legacy-compose"
|
||||
mkdir -p "$LEGACY_COMPOSE/scripts"
|
||||
cp "$REPO_ROOT/update.sh" "$REPO_ROOT/install.sh" "$LEGACY_COMPOSE/"
|
||||
cp "$REPO_ROOT/scripts/deploy-lib.sh" "$LEGACY_COMPOSE/scripts/"
|
||||
chmod +x "$LEGACY_COMPOSE/update.sh" "$LEGACY_COMPOSE/install.sh" "$LEGACY_COMPOSE/scripts/deploy-lib.sh"
|
||||
cat > "$LEGACY_COMPOSE/.env" <<'ENV'
|
||||
POSTGRES_PASSWORD=testpass
|
||||
ENV
|
||||
cat > "$LEGACY_COMPOSE/docker-compose.yml" <<'YML'
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
artex:
|
||||
image: ruoji6/artex:v0.3.32
|
||||
YML
|
||||
if ( cd "$LEGACY_COMPOSE" && ARTEX_LANG= TZ=Asia/Shanghai ./update.sh --upgrade --tag v0.3.35 --skip-git-pull --yes 2>"$TMP_DIR/legacy-zh.err" ); then
|
||||
fail "legacy 2-service docker-compose.yml should be rejected (zh)"
|
||||
fi
|
||||
assert_contains "$TMP_DIR/legacy-zh.err" "旧版单容器编排" "zh error mentions legacy compose"
|
||||
assert_contains "$TMP_DIR/legacy-zh.err" "RuoJi6/ARTEX/v0.3.35/docker-compose.yml" "zh error includes exact sync URL"
|
||||
if ( cd "$LEGACY_COMPOSE" && ARTEX_LANG= TZ=UTC ./update.sh --upgrade --tag v0.3.35 --skip-git-pull --yes 2>"$TMP_DIR/legacy-en.err" ); then
|
||||
fail "legacy 2-service docker-compose.yml should be rejected (en)"
|
||||
fi
|
||||
assert_contains "$TMP_DIR/legacy-en.err" "Detected legacy single-container" "en error mentions legacy compose"
|
||||
assert_contains "$TMP_DIR/legacy-en.err" "RuoJi6/ARTEX/v0.3.35/docker-compose.yml" "en error includes exact sync URL"
|
||||
pass "legacy docker-compose.yml rejection + compose snapshot backup"
|
||||
|
||||
echo "ALL DEPLOY/UPGRADE/ROLLBACK TESTS PASSED"
|
||||
@@ -20,9 +20,58 @@ set -u
|
||||
|
||||
cd "$(dirname "$0")" || exit 1
|
||||
|
||||
BIN=./artex
|
||||
[ -x "$BIN" ] || { echo "[artex] 找不到可执行文件 $BIN" >&2; exit 1; }
|
||||
detect_script_lang() {
|
||||
override=$(printf '%s' "${ARTEX_LANG:-}" | tr '[:upper:]' '[:lower:]')
|
||||
case "$override" in
|
||||
zh|zh_*|zh-*) printf 'zh\n'; return 0 ;;
|
||||
en|en_*|en-*) printf 'en\n'; return 0 ;;
|
||||
esac
|
||||
tz=""
|
||||
if [ -n "${TZ:-}" ]; then
|
||||
tz=${TZ#:}
|
||||
elif [ -r /etc/timezone ]; then
|
||||
tz=$(tr -d ' \t\r\n' < /etc/timezone 2>/dev/null || true)
|
||||
fi
|
||||
if [ -z "$tz" ] && [ -L /etc/localtime ]; then
|
||||
tz=$(readlink /etc/localtime 2>/dev/null || true)
|
||||
fi
|
||||
if [ -z "$tz" ] && command -v timedatectl >/dev/null 2>&1; then
|
||||
tz=$(timedatectl show -p Timezone --value 2>/dev/null || true)
|
||||
fi
|
||||
case "$tz" in
|
||||
*zoneinfo/*) tz=${tz#*zoneinfo/} ;;
|
||||
esac
|
||||
tz_lc=$(printf '%s' "$tz" | tr '[:upper:]' '[:lower:]')
|
||||
case "$tz_lc" in
|
||||
asia/shanghai|asia/chongqing|asia/chungking|asia/harbin|asia/kashgar|asia/urumqi|\
|
||||
asia/hong_kong|asia/macau|asia/macao|asia/taipei|\
|
||||
prc|roc|hongkong|etc/gmt-8|cst-8|cst-8:*|hkt|hkt-8*)
|
||||
printf 'zh\n'
|
||||
return 0
|
||||
;;
|
||||
"")
|
||||
abbr=$(date +%Z 2>/dev/null || true)
|
||||
offset=$(date +%z 2>/dev/null || true)
|
||||
if { [ "$abbr" = "CST" ] && [ "$offset" = "+0800" ]; } || [ "$abbr" = "HKT" ]; then
|
||||
printf 'zh\n'
|
||||
return 0
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
printf 'en\n'
|
||||
}
|
||||
|
||||
ARTEX_SCRIPT_LANG=$(detect_script_lang)
|
||||
msg() {
|
||||
if [ "$ARTEX_SCRIPT_LANG" = "zh" ]; then
|
||||
printf '%s' "$1"
|
||||
else
|
||||
printf '%s' "$2"
|
||||
fi
|
||||
}
|
||||
|
||||
BIN=./artex
|
||||
[ -x "$BIN" ] || { printf '%s\n' "$(msg "[artex] 找不到可执行文件 $BIN" "[artex] Executable not found: $BIN")" >&2; exit 1; }
|
||||
RESTART_CODE=75
|
||||
MAX_DELAY=60
|
||||
|
||||
@@ -58,22 +107,22 @@ while :; do
|
||||
child=0
|
||||
|
||||
if [ "$stopping" -eq 1 ]; then
|
||||
echo "[artex] 已停止"
|
||||
printf '%s\n' "$(msg "[artex] 已停止" "[artex] Stopped")"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
case "$code" in
|
||||
0)
|
||||
echo "[artex] 正常退出"
|
||||
printf '%s\n' "$(msg "[artex] 正常退出" "[artex] Exited cleanly")"
|
||||
exit 0
|
||||
;;
|
||||
"$RESTART_CODE")
|
||||
# 更新/回滚已就绪:重跑后 artex 会在启动时完成换装(见 selfupdate.Bootstrap)。
|
||||
echo "[artex] 请求重启(应用新版本)…"
|
||||
printf '%s\n' "$(msg "[artex] 请求重启(应用新版本)…" "[artex] Restart requested (applying update)...")"
|
||||
delay=1
|
||||
;;
|
||||
*)
|
||||
echo "[artex] 异常退出 (code=$code),${delay}s 后重启" >&2
|
||||
printf '%s\n' "$(msg "[artex] 异常退出 (code=$code),${delay}s 后重启" "[artex] Exited unexpectedly (code=$code), restarting in ${delay}s")" >&2
|
||||
sleep "$delay"
|
||||
delay=$((delay * 2))
|
||||
[ "$delay" -gt "$MAX_DELAY" ] && delay=$MAX_DELAY
|
||||
|
||||
@@ -11,17 +11,20 @@ cd "$(cd "$(dirname "$0")" && pwd)"
|
||||
|
||||
sync_repo(){
|
||||
[ "${ARTEX_SKIP_GIT_PULL:-0}" = "1" ] && return 0
|
||||
[ -d .git ] && command -v git >/dev/null 2>&1 || { warn "非 git 工作副本,跳过 git pull"; return 0; }
|
||||
[ "$(ask '拉取最新代码 (git pull --ff-only)? (y/n)' y)" = y ] || return 0
|
||||
[ -d .git ] && command -v git >/dev/null 2>&1 || { warn_l "非 git 工作副本,跳过 git pull" "Not a git working tree; skipping git pull"; return 0; }
|
||||
is_yes "$(ask_l '拉取最新代码 (git pull --ff-only)? (y/n)' 'Pull latest code (git pull --ff-only)? (y/n)' y)" || return 0
|
||||
if ! git pull --ff-only; then
|
||||
warn "git pull 未能快进(本地有改动或分支分叉)——请手动处理后重试,本次沿用当前代码"
|
||||
warn_l "git pull 未能快进(本地有改动或分支分叉)——请手动处理后重试,本次沿用当前代码" \
|
||||
"git pull could not fast-forward (local changes or diverged branch) -- continuing with current files"
|
||||
fi
|
||||
}
|
||||
|
||||
require_docker_env(){
|
||||
command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1 \
|
||||
|| die "未检测到 docker / docker compose,请先用 ./install.sh 安装部署"
|
||||
[ -f .env ] || die "未找到 .env,请先运行 ./install.sh 完成首次部署"
|
||||
|| die_l "未检测到 docker / docker compose,请先用 ./install.sh 安装部署" \
|
||||
"docker / docker compose not found; run ./install.sh first"
|
||||
[ -f .env ] || die_l "未找到 .env,请先运行 ./install.sh 完成首次部署" \
|
||||
".env not found; run ./install.sh for initial deployment"
|
||||
}
|
||||
|
||||
# ── ① Docker 升级(自动快照 + 失败自动回滚)─────────────────────────────
|
||||
@@ -31,21 +34,26 @@ update_docker(){
|
||||
preflight_docker
|
||||
|
||||
if [ -z "$tag" ] && [ "${ARTEX_NONINTERACTIVE:-0}" != "1" ]; then
|
||||
tag="$(ask '目标镜像 tag(回车沿用 .env / latest;如 v0.3.33)' '')"
|
||||
tag="$(ask_l '目标镜像 tag(回车沿用 .env / latest;如 v0.3.35)' 'Target image tag (Enter to keep .env / latest; e.g. v0.3.35)' '')"
|
||||
fi
|
||||
|
||||
info "正在创建升级前部署快照(用于失败自动回滚或手动回滚)…"
|
||||
validate_sandbox_compose "$COMPOSE_FILE" "$tag"
|
||||
|
||||
info_l "正在创建升级前部署快照(用于失败自动回滚或手动回滚)…" \
|
||||
"Creating pre-upgrade deployment snapshot (for auto-rollback or manual rollback)..."
|
||||
local snap_id
|
||||
snap_id="$(create_deploy_snapshot "upgrade" "$skip_db")"
|
||||
ok "已创建回滚快照:${snap_id}"
|
||||
ok_l "已创建回滚快照:${snap_id}" "Created rollback snapshot: ${snap_id}"
|
||||
|
||||
prepare_env_for_docker "$tag" .env
|
||||
prepare_migrated_workspaces ./data
|
||||
|
||||
deploy_with_rollback "$snap_id"
|
||||
ok "升级完成 → http://localhost:8787"
|
||||
info "如需回滚到升级前状态:./update.sh --rollback ${snap_id}"
|
||||
info "查看日志:docker compose -f ${COMPOSE_FILE} logs -f artex"
|
||||
ok_l "升级完成 → http://localhost:8787" "Upgrade complete -> http://localhost:8787"
|
||||
info_l "如需回滚到升级前状态:./update.sh --rollback ${snap_id}" \
|
||||
"To roll back to the previous state: ./update.sh --rollback ${snap_id}"
|
||||
info_l "查看日志:docker compose -f ${COMPOSE_FILE} logs -f artex" \
|
||||
"View logs: docker compose -f ${COMPOSE_FILE} logs -f artex"
|
||||
}
|
||||
|
||||
# ── ④ 回滚到历史部署快照 ────────────────────────────────────────────────
|
||||
@@ -54,20 +62,21 @@ interactive_rollback(){
|
||||
require_docker_env
|
||||
|
||||
if [ -z "$snap_id" ]; then
|
||||
echo "可用的部署回滚快照:"
|
||||
echo "$(msg '可用的部署回滚快照:' 'Available rollback snapshots:')"
|
||||
list_deploy_snapshots
|
||||
local latest=""
|
||||
[ -f "${DEPLOY_STATE_DIR}/latest" ] && latest="$(cat "${DEPLOY_STATE_DIR}/latest")"
|
||||
[ -n "$latest" ] || die "当前没有任何可回滚的部署快照"
|
||||
snap_id="$(ask '要回滚的快照 ID(回车选最新)' "$latest")"
|
||||
[ -n "$latest" ] || die_l "当前没有任何可回滚的部署快照" "No rollback snapshots available"
|
||||
snap_id="$(ask_l '要回滚的快照 ID(回车选最新)' 'Snapshot ID to roll back to (Enter for latest)' "$latest")"
|
||||
fi
|
||||
|
||||
local snap_dir="${DEPLOY_SNAP_DIR}/${snap_id}"
|
||||
[ -f "${snap_dir}/meta.env" ] || die "快照不存在:${snap_id}"
|
||||
[ -f "${snap_dir}/meta.env" ] || die_l "快照不存在:${snap_id}" "Snapshot not found: ${snap_id}"
|
||||
|
||||
if [ "$restore_db" != "1" ] && [ "$(env_get HAS_PG_DUMP "${snap_dir}/meta.env")" = "1" ] && [ "${ARTEX_NONINTERACTIVE:-0}" != "1" ]; then
|
||||
warn "当前版本与上一版本数据库结构前向/后向兼容,通常无需覆盖数据库。"
|
||||
if [ "$(ask '是否同时用快照中的 postgres.sql.gz 覆盖恢复数据库? (y/n)' n)" = "y" ]; then
|
||||
warn_l "当前版本与上一版本数据库结构前向/后向兼容,通常无需覆盖数据库。" \
|
||||
"The database schema is forward/backward compatible; restoring the DB dump is usually unnecessary."
|
||||
if is_yes "$(ask_l '是否同时用快照中的 postgres.sql.gz 覆盖恢复数据库? (y/n)' 'Also overwrite and restore the database from snapshot postgres.sql.gz? (y/n)' n)"; then
|
||||
restore_db=1
|
||||
fi
|
||||
fi
|
||||
@@ -77,31 +86,37 @@ interactive_rollback(){
|
||||
|
||||
# ── ⑤ 本地编译更新 ──────────────────────────────────────────────────────
|
||||
update_local(){
|
||||
command -v go >/dev/null 2>&1 || die "未检测到 Go(>=1.26):https://go.dev/dl/"
|
||||
[ -f config.json ] || warn "未找到 config.json——若首次部署请改用 ./install.sh"
|
||||
command -v go >/dev/null 2>&1 || die_l "未检测到 Go(>=1.26):https://go.dev/dl/" \
|
||||
"Go (>=1.26) not found: https://go.dev/dl/"
|
||||
[ -f config.json ] || warn_l "未找到 config.json——若首次部署请改用 ./install.sh" \
|
||||
"config.json not found -- run ./install.sh for initial setup"
|
||||
ok "Go: $(go version)"
|
||||
|
||||
if [ -x ./artex ]; then
|
||||
cp ./artex ./artex.old
|
||||
ok "已备份当前二进制 → ./artex.old(如需回滚可执行 mv ./artex.old ./artex 后重启)"
|
||||
ok_l "已备份当前二进制 → ./artex.old(如需回滚可执行 mv ./artex.old ./artex 后重启)" \
|
||||
"Backed up current binary -> ./artex.old (to roll back: mv ./artex.old ./artex and restart)"
|
||||
fi
|
||||
|
||||
if command -v npm >/dev/null 2>&1; then
|
||||
info "重建前端静态产物…"
|
||||
info_l "重建前端静态产物…" "Rebuilding static frontend assets..."
|
||||
( cd web && npm ci && npm run build:static )
|
||||
rm -rf server/webui/dist && cp -r web/out server/webui/dist
|
||||
info "重新编译内嵌单二进制…"
|
||||
info_l "重新编译内嵌单二进制…" "Rebuilding embedded single binary..."
|
||||
CGO_ENABLED=0 go build -tags embedui -trimpath -o artex ./cmd/artex
|
||||
else
|
||||
warn "未检测到 npm:编译**不内嵌前端**的后端(前端需另跑 npm run dev)"
|
||||
warn_l "未检测到 npm:编译**不内嵌前端**的后端(前端需另跑 npm run dev)" \
|
||||
"npm not found: building backend WITHOUT embedded frontend (run npm run dev separately)"
|
||||
CGO_ENABLED=0 go build -o artex ./cmd/artex
|
||||
fi
|
||||
ok "编译完成 → ./artex"
|
||||
warn "请重启正在运行的 artex 进程以生效(重启时会自动迁移 schema)"
|
||||
ok_l "编译完成 → ./artex" "Build complete -> ./artex"
|
||||
warn_l "请重启正在运行的 artex 进程以生效(重启时会自动迁移 schema)" \
|
||||
"Please restart the running artex process to take effect (schema migrates automatically on startup)"
|
||||
}
|
||||
|
||||
usage(){
|
||||
cat <<'USAGE'
|
||||
if [ "$ARTEX_SCRIPT_LANG" = "zh" ]; then
|
||||
cat <<'USAGE'
|
||||
用法: ./update.sh [动作] [选项]
|
||||
|
||||
动作(不传则进入交互菜单):
|
||||
@@ -111,7 +126,7 @@ usage(){
|
||||
--local 本地 Go 重新编译更新
|
||||
|
||||
选项:
|
||||
--tag <TAG> 指定目标镜像版本 tag(如 v0.3.33 / latest)
|
||||
--tag <TAG> 指定目标镜像版本 tag(如 v0.3.34 / latest)
|
||||
--restore-db 配合 --rollback 同时恢复快照中的 PostgreSQL 备份
|
||||
--no-db-backup 创建快照时跳过 pg_dump
|
||||
--skip-pull 跳过镜像拉取
|
||||
@@ -119,6 +134,26 @@ usage(){
|
||||
-y, --yes 非交互模式
|
||||
-h, --help 显示本帮助
|
||||
USAGE
|
||||
else
|
||||
cat <<'USAGE'
|
||||
Usage: ./update.sh [action] [options]
|
||||
|
||||
Actions (opens interactive menu if omitted):
|
||||
--upgrade Upgrade Docker deployment (creates rollback snapshot)
|
||||
--rollback [SNAPSHOT_ID] Roll back to the latest or specified snapshot
|
||||
--list-snapshots List all available rollback snapshots
|
||||
--local Rebuild and update locally with Go
|
||||
|
||||
Options:
|
||||
--tag <TAG> Target image tag (e.g. v0.3.34 / latest)
|
||||
--restore-db With --rollback, also restore the snapshot PostgreSQL dump
|
||||
--no-db-backup Skip pg_dump when creating a snapshot
|
||||
--skip-pull Skip pulling Docker images
|
||||
--skip-git-pull Skip git pull
|
||||
-y, --yes Non-interactive mode
|
||||
-h, --help Show this help
|
||||
USAGE
|
||||
fi
|
||||
}
|
||||
|
||||
ACTION=""
|
||||
@@ -139,14 +174,14 @@ while [ "$#" -gt 0 ]; do
|
||||
;;
|
||||
--list-snapshots) ACTION="list-snapshots" ;;
|
||||
--local) ACTION="local" ;;
|
||||
--tag) shift; [ "$#" -gt 0 ] || die "--tag 需要参数"; OPT_TAG="$1" ;;
|
||||
--tag) shift; [ "$#" -gt 0 ] || die_l "--tag 需要参数" "--tag requires a value"; OPT_TAG="$1" ;;
|
||||
--restore-db) OPT_RESTORE_DB=1 ;;
|
||||
--no-db-backup) OPT_SKIP_DB=1 ;;
|
||||
--skip-pull) export ARTEX_SKIP_PULL=1 ;;
|
||||
--skip-git-pull) export ARTEX_SKIP_GIT_PULL=1 ;;
|
||||
-y|--yes) export ARTEX_NONINTERACTIVE=1 ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
*) die "未知参数:$1(使用 --help 查看帮助)" ;;
|
||||
*) die_l "未知参数:$1(使用 --help 查看帮助)" "Unknown option: $1 (use --help for usage)" ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
@@ -173,14 +208,14 @@ case "$ACTION" in
|
||||
esac
|
||||
|
||||
echo "=========================================="
|
||||
echo " ARTEX 升级与回滚"
|
||||
echo " 1) Docker 升级(自动创建回滚快照)"
|
||||
echo " 2) 回滚到历史部署快照"
|
||||
echo " 3) 本地更新(Go 重新编译)"
|
||||
echo "$(msg ' ARTEX 升级与回滚' ' ARTEX Upgrade & Rollback')"
|
||||
echo "$(msg ' 1) Docker 升级(自动创建回滚快照)' ' 1) Docker upgrade (auto-creates rollback snapshot)')"
|
||||
echo "$(msg ' 2) 回滚到历史部署快照' ' 2) Roll back to a previous snapshot')"
|
||||
echo "$(msg ' 3) 本地更新(Go 重新编译)' ' 3) Local update (rebuild with Go)')"
|
||||
echo "=========================================="
|
||||
case "$(ask '选择' 1)" in
|
||||
case "$(ask_l '选择' 'Select' 1)" in
|
||||
1) sync_repo; update_docker "$OPT_TAG" "$OPT_SKIP_DB" ;;
|
||||
2) interactive_rollback "$OPT_SNAP" "$OPT_RESTORE_DB" ;;
|
||||
3) sync_repo; update_local ;;
|
||||
*) die "无效选择" ;;
|
||||
*) die_l "无效选择" "Invalid selection" ;;
|
||||
esac
|
||||
@@ -7,6 +7,8 @@ import Link from "next/link";
|
||||
import {
|
||||
ActivityIcon,
|
||||
BoxIcon,
|
||||
CheckIcon,
|
||||
CopyIcon,
|
||||
CpuIcon,
|
||||
ExternalLinkIcon,
|
||||
HardDriveIcon,
|
||||
@@ -15,7 +17,9 @@ import {
|
||||
RotateCcwIcon,
|
||||
SearchIcon,
|
||||
Settings2Icon,
|
||||
ShieldCheckIcon,
|
||||
SquareIcon,
|
||||
TerminalIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
@@ -87,7 +91,8 @@ export default function SandboxPage() {
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
const [pruning, setPruning] = React.useState(false);
|
||||
const [busyKey, setBusyKey] = React.useState<string>("");
|
||||
|
||||
const [upgradeTag, setUpgradeTag] = React.useState("v0.3.35");
|
||||
const [copiedCmd, setCopiedCmd] = React.useState<"" | "git" | "sync">("");
|
||||
// Filters
|
||||
const [scopeFilter, setScopeFilter] = React.useState<"all" | "task" | "session">("all");
|
||||
const [stateFilter, setStateFilter] = React.useState<"all" | "running" | "stopped">("all");
|
||||
@@ -165,6 +170,44 @@ export default function SandboxPage() {
|
||||
void load(false, true, true);
|
||||
}, [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 gitUpgradeCommand = `git pull --ff-only && ./update.sh --upgrade --tag ${upgradeTag} --skip-git-pull`;
|
||||
const syncUpgradeCommand = [
|
||||
"(",
|
||||
" set -e",
|
||||
" mkdir -p scripts",
|
||||
" if [ -f docker-compose.yml ]; then cp docker-compose.yml docker-compose.yml.bak; fi",
|
||||
" for f in docker-compose.yml update.sh scripts/deploy-lib.sh scripts/artex-sandbox-firewall.sh; do",
|
||||
` curl -fsSL "https://raw.githubusercontent.com/RuoJi6/ARTEX/${upgradeTag}/$f" -o "$f"`,
|
||||
" done",
|
||||
" chmod +x update.sh scripts/deploy-lib.sh scripts/artex-sandbox-firewall.sh",
|
||||
`) && ./update.sh --upgrade --tag ${upgradeTag} --skip-git-pull`,
|
||||
].join("\n");
|
||||
|
||||
const handleCopyUpgradeCommand = async (kind: "git" | "sync", cmd: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(cmd);
|
||||
setCopiedCmd(kind);
|
||||
toast.success(L("升级命令已复制", "Upgrade command copied"));
|
||||
window.setTimeout(() => setCopiedCmd((prev) => (prev === kind ? "" : prev)), 2000);
|
||||
} catch {
|
||||
toast.error(L("复制失败,请手动复制命令", "Copy failed, please copy manually"));
|
||||
}
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!autoRefresh) return;
|
||||
const timer = window.setInterval(() => {
|
||||
@@ -351,8 +394,8 @@ export default function SandboxPage() {
|
||||
`Manage lifecycle and resource usage for isolated task and chat containers (network: ${status.network}, ICC disabled).`,
|
||||
)
|
||||
: 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>
|
||||
</div>
|
||||
@@ -394,6 +437,88 @@ export default function SandboxPage() {
|
||||
</div>
|
||||
) : 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.5">
|
||||
<div className="space-y-1.5">
|
||||
<p className="font-medium text-foreground text-xs">
|
||||
{L("方式一:git clone 部署目录", "Option 1: Git clone deployment")}
|
||||
</p>
|
||||
<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>{gitUpgradeCommand}</code>
|
||||
</pre>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 shrink-0 gap-1.5 px-2.5 text-xs"
|
||||
onClick={() => void handleCopyUpgradeCommand("git", gitUpgradeCommand)}
|
||||
>
|
||||
{copiedCmd === "git" ? (
|
||||
<CheckIcon className="size-3.5 text-emerald-500" />
|
||||
) : (
|
||||
<CopyIcon className="size-3.5" />
|
||||
)}
|
||||
{copiedCmd === "git" ? L("已复制", "Copied") : L("复制命令", "Copy")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<p className="font-medium text-foreground text-xs">
|
||||
{L(
|
||||
"方式二:非 git 部署目录(仅含 docker-compose.yml 与 .env,自动备份并同步新版编排与脚本)",
|
||||
"Option 2: Non-Git deployment (backs up docker-compose.yml and syncs latest compose & scripts)",
|
||||
)}
|
||||
</p>
|
||||
<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>{syncUpgradeCommand}</code>
|
||||
</pre>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 shrink-0 gap-1.5 px-2.5 text-xs"
|
||||
onClick={() => void handleCopyUpgradeCommand("sync", syncUpgradeCommand)}
|
||||
>
|
||||
{copiedCmd === "sync" ? (
|
||||
<CheckIcon className="size-3.5 text-emerald-500" />
|
||||
) : (
|
||||
<CopyIcon className="size-3.5" />
|
||||
)}
|
||||
{copiedCmd === "sync" ? L("已复制", "Copied") : L("复制命令", "Copy")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-muted-foreground text-xs leading-relaxed">
|
||||
{L(
|
||||
"升级会保留原有 PostgreSQL 数据、./data 与 ./skills,并启动 4 个服务容器(postgres、docker-socket-proxy、artex、artex-gateway)。切换后无法回滚但会显著提高运行安全性;完成后刷新本页即可进入 Docker 沙箱模式。",
|
||||
"Preserves PostgreSQL data, ./data, and ./skills, and starts 4 services (postgres, docker-socket-proxy, artex, artex-gateway). This switch is irreversible but significantly improves isolation security; refresh this page after upgrading.",
|
||||
)}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : null}
|
||||
|
||||
{/* Summary KPI cards */}
|
||||
{status?.enabled ? (
|
||||
<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 {
|
||||
BoxIcon,
|
||||
CheckIcon,
|
||||
CopyIcon,
|
||||
ExternalLinkIcon,
|
||||
PlayIcon,
|
||||
RefreshCwIcon,
|
||||
RotateCcwIcon,
|
||||
SquareIcon,
|
||||
TerminalIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
@@ -53,7 +56,8 @@ export function SandboxCard() {
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
const [pruning, setPruning] = React.useState(false);
|
||||
const [busyKey, setBusyKey] = React.useState("");
|
||||
|
||||
const [upgradeTag, setUpgradeTag] = React.useState("v0.3.35");
|
||||
const [copiedCmd, setCopiedCmd] = React.useState<"" | "git" | "sync">("");
|
||||
const [image, setImage] = React.useState("");
|
||||
const [memoryMB, setMemoryMB] = React.useState("2048");
|
||||
const [cpus, setCpus] = React.useState("2");
|
||||
@@ -102,6 +106,34 @@ export function SandboxCard() {
|
||||
void load(true);
|
||||
}, [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 gitUpgradeCommand = `git pull --ff-only && ./update.sh --upgrade --tag ${upgradeTag} --skip-git-pull`;
|
||||
const syncUpgradeCommand = `(set -e; mkdir -p scripts; if [ -f docker-compose.yml ]; then cp docker-compose.yml docker-compose.yml.bak; fi; for f in docker-compose.yml update.sh scripts/deploy-lib.sh scripts/artex-sandbox-firewall.sh; do curl -fsSL "https://raw.githubusercontent.com/RuoJi6/ARTEX/${upgradeTag}/$f" -o "$f"; done; chmod +x update.sh scripts/deploy-lib.sh scripts/artex-sandbox-firewall.sh) && ./update.sh --upgrade --tag ${upgradeTag} --skip-git-pull`;
|
||||
|
||||
const handleCopyUpgradeCommand = async (kind: "git" | "sync", cmd: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(cmd);
|
||||
setCopiedCmd(kind);
|
||||
toast.success(L("升级命令已复制", "Upgrade command copied"));
|
||||
window.setTimeout(() => setCopiedCmd((prev) => (prev === kind ? "" : prev)), 2000);
|
||||
} catch {
|
||||
toast.error(L("复制失败,请手动复制命令", "Copy failed, please copy manually"));
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
@@ -235,8 +267,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.`,
|
||||
)
|
||||
: 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>
|
||||
</CardHeader>
|
||||
@@ -248,6 +280,65 @@ export function SandboxCard() {
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{status && !status.enabled ? (
|
||||
<div className="space-y-2.5 rounded-md border border-amber-500/40 bg-amber-500/5 p-3">
|
||||
<p className="text-muted-foreground text-xs">
|
||||
{L(
|
||||
"在宿主机原部署目录执行以下命令升级至沙箱隔离版(保留数据库、./data 与 ./skills,需同步新版 docker-compose.yml):",
|
||||
"Run one of the commands below in your host deployment directory to upgrade to the sandbox edition (preserves DB, ./data, and ./skills; requires latest docker-compose.yml):",
|
||||
)}
|
||||
</p>
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium text-foreground text-[11px]">
|
||||
{L("Git clone 部署目录", "Git clone deployment")}
|
||||
</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">{gitUpgradeCommand}</code>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 shrink-0 gap-1 px-2 text-xs"
|
||||
onClick={() => void handleCopyUpgradeCommand("git", gitUpgradeCommand)}
|
||||
>
|
||||
{copiedCmd === "git" ? (
|
||||
<CheckIcon className="size-3.5 text-emerald-500" />
|
||||
) : (
|
||||
<CopyIcon className="size-3.5" />
|
||||
)}
|
||||
{copiedCmd === "git" ? L("已复制", "Copied") : L("复制", "Copy")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium text-foreground text-[11px]">
|
||||
{L("非 Git 部署目录(自动同步编排与脚本)", "Non-Git deployment (syncs compose & scripts)")}
|
||||
</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">{syncUpgradeCommand}</code>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 shrink-0 gap-1 px-2 text-xs"
|
||||
onClick={() => void handleCopyUpgradeCommand("sync", syncUpgradeCommand)}
|
||||
>
|
||||
{copiedCmd === "sync" ? (
|
||||
<CheckIcon className="size-3.5 text-emerald-500" />
|
||||
) : (
|
||||
<CopyIcon className="size-3.5" />
|
||||
)}
|
||||
{copiedCmd === "sync" ? L("已复制", "Copied") : L("复制", "Copy")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{status?.enabled ? (
|
||||
<>
|
||||
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
|
||||
|
||||
@@ -56,6 +56,7 @@ export function UpdateCard() {
|
||||
const { t, liveT } = useLiveTranslation();
|
||||
const [info, setInfo] = React.useState<UpdateCheck | null>(null);
|
||||
const [checking, setChecking] = React.useState(true);
|
||||
const [sandboxEnabled, setSandboxEnabled] = React.useState<boolean | null>(null);
|
||||
const [confirmOpen, setConfirmOpen] = React.useState(false);
|
||||
const [progress, setProgress] = React.useState<UpdateProgress | null>(null);
|
||||
// 与 progress 分开:暂存完成后进程就没了,SSE 会断,此时要切到轮询 /api/version。
|
||||
@@ -86,6 +87,21 @@ export function UpdateCard() {
|
||||
};
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
let active = true;
|
||||
api
|
||||
.sandboxStatus(false)
|
||||
.then((st) => {
|
||||
if (active) setSandboxEnabled(Boolean(st.enabled));
|
||||
})
|
||||
.catch(() => {
|
||||
// keep null if sandbox status is unavailable
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => () => streamRef.current?.close(), []);
|
||||
|
||||
// quiet 同时决定要不要绕过后端缓存:进页面时的自动检查用缓存(顶栏刚查过),
|
||||
@@ -458,13 +474,15 @@ export function UpdateCard() {
|
||||
<AlertDialogDescription asChild>
|
||||
<div className="space-y-2.5 text-left">
|
||||
<p>{t("settings.updateInterruptWarning")}</p>
|
||||
<div className="space-y-1 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-amber-800 text-xs dark:text-amber-300">
|
||||
<p className="flex items-center gap-1.5 font-medium">
|
||||
<ShieldCheckIcon className="size-4 shrink-0" />
|
||||
{t("settings.standaloneToSandboxTitle")}
|
||||
</p>
|
||||
<p className="leading-relaxed">{t("settings.standaloneToSandboxWarning")}</p>
|
||||
</div>
|
||||
{info?.mode === "docker" && sandboxEnabled === false && (
|
||||
<div className="space-y-1 rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-amber-800 text-xs dark:text-amber-300">
|
||||
<p className="flex items-center gap-1.5 font-medium">
|
||||
<ShieldCheckIcon className="size-4 shrink-0" />
|
||||
{t("settings.standaloneToSandboxTitle")}
|
||||
</p>
|
||||
<p className="leading-relaxed">{t("settings.standaloneToSandboxWarning")}</p>
|
||||
</div>
|
||||
)}
|
||||
{info?.mode === "docker" && (
|
||||
<p className="text-muted-foreground text-xs">{t("settings.dockerUpdateWarning")}</p>
|
||||
)}
|
||||
|
||||
Reference in new issue
Block a user