Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
.git
.github
ui/node_modules
ui/dist
*.db
*.db-wal
*.db-shm
*.secrets.json
opsup
opsup-arm64
43 changes: 43 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
name: CI

on:
push:
branches: [main]
pull_request:

permissions:
contents: read

jobs:
verify:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
cache-dependency-path: ui/package-lock.json
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache: true
- name: Install frontend dependencies
working-directory: ui
run: npm ci
- name: Frontend tests
working-directory: ui
run: npm test
- name: Typecheck and build frontend
working-directory: ui
run: npm run build
- name: Check Go formatting
run: test -z "$(gofmt -l main.go internal)"
- name: Vet and race-test Go
run: |
go vet ./...
go test -race ./...
- name: Build binary
run: CGO_ENABLED=1 go build -trimpath -o opsup .
- name: Build container
run: docker build -t opsup:ci .
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ opsup-arm64
*.db
*.db-shm
*.db-wal
*.secrets.json

# Frontend
ui/node_modules/
Expand Down
39 changes: 24 additions & 15 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,28 +33,28 @@ CGO is required because of `mattn/go-sqlite3`. Frontend must be built first —

## Architecture

**Startup flow** (main.go): `config.Load()` → `database.Init()` → `api.SetupRouter()` → `router.Run()`
**Startup flow** (main.go): load persistent configuration → versioned SQLite migrations → validate/upgrade credential encryption → HTTP server with request cancellation and graceful shutdown.

**Backend** (internal/):
- `config/` — Environment variable config (DB path, JWT secret, encryption key, listen address)
- `database/` — SQLite init with WAL mode, auto-migrations in `migrations.go`
- `config/` — Environment overrides and persistent random secrets
- `database/` — SQLite WAL, transactional schema migrations and legacy credential upgrade
- `models/` — User and Server CRUD (parameterized queries)
- `auth/` — JWT sign/verify + bcrypt hashing + Gin middleware
- `crypto/` — AES-256-GCM encrypt/decrypt for private key storage
- `sshclient/` — SSH dial (direct + jump host via `DialViaJump`) and PTY session
- `terminal/` — In-memory registry of active terminal sessions (sync.Mutex)
- `api/` — Gin router with handlers: auth, server CRUD, WebSocket terminal, SFTP
- `crypto/` — AES-256-GCM credential storage
- `sshclient/` — Pinned SSH identities, context-bound direct/jump connections and PTY sessions
- `terminal/` — Registry helper; handlers currently own their connections directly
- `api/` — Authentication, server CRUD, bounded WebSocket terminals and atomic SFTP uploads

**Frontend** (ui/): React 19 + Ant Design 6 + xterm.js 6. Key pages: LoginPage, SetupPage, MainPage (server sidebar + terminal tabs).
**Frontend** (ui/): React 19 + Ant Design 6 + xterm.js 6. MainPage, terminals and dialogs are lazy-loaded; inactive terminal tabs stay mounted.

**WebSocket terminal protocol**: Binary frames, first byte is message type (0x00=data, 0x01=resize, 0x02=error, 0x03=status, 0x04=connected). JWT auth via query param.
**WebSocket terminal protocol**: Binary frames, first byte is message type (0x00=data, 0x01=resize, 0x02=error, 0x03=status, 0x04=connected). JWT auth via query param. Messages are limited to 64 KiB; frontend stdin payloads are chunked to 16 KiB.

## Key Design Decisions

- Private keys never reach the browser — key reuse (`copy_key_from`) copies encrypted data server-side
- Server jump chains use self-referential `jump_server_id` foreign key
- Credential reuse (`copy_key_from`) copies encrypted data server-side; API responses omit all credentials
- One direct jump host is supported via `jump_server_id`; nested jump chains are rejected
- Frontend embedded as `//go:embed ui/dist` for single-binary deployment
- SQLite with WAL mode for concurrent read/write
- SQLite uses WAL and a single pooled connection with a busy timeout

## Deploy to Target Device

Expand All @@ -75,7 +75,16 @@ Service restart: `ssh root@192.168.100.1 "/etc/init.d/opsup restart"`

| Variable | Default | Description |
|----------|---------|-------------|
| `OPSUP_DB_PATH` | `./opsup.db` | SQLite database path |
| `OPSUP_JWT_SECRET` | random | JWT signing secret |
| `OPSUP_ENCRYPTION_KEY` | random | 64-char hex for AES-256-GCM |
| `OPSUP_DB_PATH` | executable directory/opsup.db | SQLite database path |
| `OPSUP_JWT_SECRET` | persisted random | At least 32 bytes when overridden |
| `OPSUP_ENCRYPTION_KEY` | persisted random | 64-char hex for AES-256-GCM; preserve custom keys during upgrades |
| `OPSUP_SECRETS_PATH` | <DB path>.secrets.json | Auto-created 0600 key file; back up with the database |
| `OPSUP_LISTEN` | `:8080` | HTTP listen address |

## Safety and verification

- Read README_CN.md or README.md before upgrading data. Old default-key credentials are transactionally re-encrypted on startup; custom encryption keys must stay unchanged.
- SSH endpoints require independently verified SHA256 host fingerprints, including jump hosts. Never bypass host-key verification to make a connection work.
- `make clean` preserves data. `make reset-data` is explicitly destructive and requires `CONFIRM=DELETE` and `DB_PATH`.
- Run `make test` for frontend typecheck/build/tests plus Go vet/race tests. Build the frontend before testing the root Go package because of `go:embed`.
- Login and setup are rate-limited; initialize privately before enabling public HTTPS access. Proxy logs must redact WebSocket query tokens.
20 changes: 4 additions & 16 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,39 +1,27 @@
# ---- 构建阶段 ----
FROM --platform=$BUILDPLATFORM node:20-alpine AS frontend

FROM --platform=$BUILDPLATFORM node:22-alpine AS frontend
WORKDIR /build/ui
COPY ui/package.json ui/package-lock.json ./
RUN npm ci
COPY ui/ ./
RUN npm run build

FROM --platform=$BUILDPLATFORM golang:1.25-alpine AS backend

ARG TARGETPLATFORM
FROM golang:1.25-alpine AS backend
RUN apk add --no-cache gcc musl-dev

WORKDIR /build
COPY go.mod go.sum ./
RUN go mod download
COPY main.go .
COPY internal/ internal/
COPY --from=frontend /build/ui/dist/ ui/dist/
RUN CGO_ENABLED=1 go build -trimpath -ldflags="-s -w" -o opsup .

RUN CGO_ENABLED=1 go build -ldflags="-s -w" -o opsup .

# ---- 运行阶段 ----
FROM alpine:3.21

RUN apk add --no-cache ca-certificates tzdata

WORKDIR /app
COPY --from=backend /build/opsup .

VOLUME /data

ENV OPSUP_DB_PATH=/data/opsup.db
ENV OPSUP_LISTEN=:8080

ENV GIN_MODE=release
EXPOSE 8080

ENTRYPOINT ["./opsup"]
25 changes: 16 additions & 9 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
.PHONY: init tidy build build-frontend dev clean
.PHONY: init tidy build build-frontend dev test clean reset-data

init:
go mod tidy

tidy:
init tidy:
go mod tidy

build-frontend:
cd ui && npm install && npm run build
cd ui && npm ci && npm run build

build: build-frontend
CGO_ENABLED=1 go build -o opsup .
CGO_ENABLED=1 go build -trimpath -o opsup .

dev:
go run main.go
OPSUP_DB_PATH="$${OPSUP_DB_PATH:-$(CURDIR)/dev-data/opsup.db}" go run .

test: build-frontend
go vet ./...
go test -race ./...
cd ui && npm test

clean:
rm -f opsup opsup.db
rm -f opsup opsup-arm64
rm -rf ui/dist ui/node_modules

reset-data:
@test "$(CONFIRM)" = "DELETE" || (printf '%s\n' 'Destructive: stop OpsUp, back up your data, then run make reset-data CONFIRM=DELETE DB_PATH=/path/to/opsup.db'; exit 1)
@test -n "$(DB_PATH)" || (printf '%s\n' 'DB_PATH is required'; exit 1)
rm -f -- "$(DB_PATH)" "$(DB_PATH)-wal" "$(DB_PATH)-shm"
92 changes: 71 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,39 +138,89 @@ Binary frames, first byte is message type:

## Quick Start

Requires Go 1.25+, a C compiler for SQLite/CGO, make, and Node.js 22.22.2+ (or 24.15+).

```bash
# Build (frontend + backend)
make build
# Initialize the administrator locally before exposing the service through HTTPS.
OPSUP_LISTEN=127.0.0.1:8080 OPSUP_DB_PATH=./data/opsup.db ./opsup
```

# Run (default port 8080)
./opsup

# Custom configuration
OPSUP_LISTEN=:9090 \
OPSUP_JWT_SECRET=your-secret \
OPSUP_ENCRYPTION_KEY=0123456789abcdef...(64-char hex) \
./opsup
For development, run `make build-frontend` first, then run these in separate terminals:

# Development mode (run separately)
cd ui && npm run dev # Frontend at localhost:5173
go run main.go # Backend at localhost:8080
```bash
cd ui && npm run dev
# From the repository root; keep data outside go run's temporary executable directory.
OPSUP_DB_PATH="$PWD/dev-data/opsup.db" go run .
```

### Docker
Vite proxies both HTTP and WebSocket requests under `/api`.

### Configuration and backups

| Variable | Default / requirement |
|---|---|
| `OPSUP_DB_PATH` | `opsup.db` next to the executable |
| `OPSUP_LISTEN` | `:8080` |
| `OPSUP_SECRETS_PATH` | `<database path>.secrets.json`, generated once with mode `0600` |
| `OPSUP_JWT_SECRET` | Persistent random secret when unset; overrides require at least 32 bytes and must not use the old default |
| `OPSUP_ENCRYPTION_KEY` | Persistent random key when unset; overrides require 64 hexadecimal characters |

**Back up the database and its encryption key together.** Never regenerate or delete the key on restart. Environment-provided keys must remain stable in your deployment's secret manager. Keep secret files out of Git. No secret file is created when both keys are supplied through the environment.

Docker's `/data` volume persists both the default database and secret file:

```bash
docker build -t opsup .
docker run -d -p 8080:8080 -v opsup-data:/data opsup
docker run -d -p 127.0.0.1:8080:8080 -v opsup-data:/data opsup
```

## Security
### Upgrading existing installations

1. Stop the old service and back up the database (including any remaining WAL files) and any custom encryption key.
2. If you previously configured a custom `OPSUP_ENCRYPTION_KEY`, continue supplying that exact key.
3. If you used the old public default key, remove any explicit old-default setting. Startup generates a persistent random key and transactionally re-encrypts legacy credentials.
4. If any credential cannot be decrypted, startup stops without partially changing credentials. Restore the original key and retry; do not delete data or the secret file.
5. The default JWT key changes, requiring login again. Enroll trusted SSH fingerprints for each target and jump server before connecting.

### SSH host fingerprints

Enter the expected `SHA256:…` host fingerprint in the server form. Verify it through a trusted console, for example:

```bash
for key in /etc/ssh/ssh_host_*_key.pub; do
ssh-keygen -lf "$key"
done
```

Connections without an enrolled fingerprint are rejected and report the observed fingerprint for comparison. **Do not trust that observation without independent verification.** Changed keys are rejected too; update the saved fingerprint only after confirming a legitimate rotation. Targets and jump hosts are checked independently.

### SFTP uploads and connection limits

- One direct jump host is supported; nested jump chains are rejected.
- Upload request bodies are capped at 256 MiB, including multipart overhead. Each SFTP operation has a fifteen-minute limit.
- Uploads write private temporary files before publishing. Replacing a regular file preserves permissions and UID/GID; metadata failures abort replacement. New files use `0600`; symlinks are not overwritten.
- Servers without POSIX rename support accept new files only, not overwrites. Transport loss may leave `.opsup-upload-*` files; remove them only after confirming no upload is active.

## Verification and maintenance

```bash
make test # Frontend typecheck/build/tests and Go vet/race tests
make clean # Build/dependency cleanup only; preserves data and secrets
# Destructive: stop the service and back up data first.
make reset-data CONFIRM=DELETE DB_PATH=/absolute/path/to/opsup.db
```

GitHub Actions verifies tests, Go formatting, types, binary builds, and Docker builds.

## Security boundaries

- **Encrypted private key storage**: AES-256-GCM, key loaded from environment variable
- **Password hashing**: bcrypt
- **JWT authentication**: 24-hour expiry, WebSocket auth via query param
- **SQL injection prevention**: Parameterized queries throughout
- **WebSocket concurrency safety**: Write operations serialized via sync.Mutex
- **No client-side key exposure**: Key reuse copies encrypted data server-side, never sent to the browser
- SSH private keys and passwords use AES-256-GCM storage. APIs return neither credentials nor their ciphertext. Administrator passwords use bcrypt.
- New administrator passwords require at least 12 characters and at most 72 UTF-8 bytes. First-user creation is atomic under concurrent requests.
- Login and setup are rate-limited by source IP. Forwarded IP headers are not trusted by default, so clients behind a reverse proxy share its quota.
- JWTs expire after 24 hours. WebSocket authentication still uses a query parameter. Application access logs omit query strings; **configure reverse-proxy logs to redact tokens or omit full terminal request URLs too**.
- The application is same-origin, without wildcard CORS. Use HTTPS and never expose an uninitialized installation to the public internet.
- This remains a shared-administrator server manager, not a multi-tenant authorization system. SFTP access is limited by the remote SSH account's permissions.

## License

Expand Down
Loading
Loading