This commit is contained in:
2026-05-17 04:54:34 +00:00
commit 64f4f3c5d4
12 changed files with 2624 additions and 0 deletions
+27
View File
@@ -0,0 +1,27 @@
# ---> Go
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
*test*
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
# Go workspace file
go.work
go.work.sum
# env file
.env
+310
View File
@@ -0,0 +1,310 @@
# CrowdSec Dashy — Project Plan
> Pure Go · No NPM · Tailwind CDN · Zero third-party Go packages (except SQLite if needed)
---
## 1. Architecture Overview
### Data Access — Two Layers
| Layer | What it covers | Auth |
|---|---|---|
| **CrowdSec LAPI** (REST, `net/http`) | Decisions CRUD, Alerts read/delete, health check | Machine login + password → JWT |
| **cscli exec** (`os/exec`) | Bouncers, Machines, Hub (collections/parsers/scenarios), Metrics | Binary path (mounted volume in Docker) |
> **Critical finding**: `cscli bouncers add/delete/list`, `machines add/delete/list`, and all `hub` commands hit the database directly and are **not** exposed through the REST API. Any Docker deployment must bind-mount the `cscli` binary or the app must gracefully degrade those sections.
### Deployment Modes
```
Mode A — Sidecar Docker (recommended)
crowdsec container ←→ crowdsec-dashy container
- shared Docker network (LAPI at http://crowdsec:8080)
- /usr/local/bin/cscli bind-mounted read-only from host
- CROWDSEC_API_LOGIN / PASSWORD as machine credentials
Mode B — Host binary
- Direct localhost:8080 LAPI
- cscli already on PATH
```
### No SQLite needed
All state lives in CrowdSec's own database. No local DB required.
---
## 2. Environment Variables
```bash
PORT=:8080 # UI listen address
CROWDSEC_API_URL=http://localhost:8080 # LAPI base URL
CROWDSEC_API_LOGIN=crowdsec-dashy # machine login (create with cscli machines add)
CROWDSEC_API_PASSWORD=changeme # machine password
CSCLI_PATH=/usr/local/bin/cscli # path to cscli binary
UI_USERNAME=admin # basic-auth for the UI itself
UI_PASSWORD=changeme # basic-auth for the UI itself
UI_SESSION_SECRET=random32chars # HMAC session signing key
POLL_INTERVAL_SEC=15 # dashboard live-poll interval
```
---
## 3. Project Structure
```
crowdsec-dashy/
├── go.mod (module crowdsec-dashy, go 1.22)
├── Dockerfile
├── docker-compose.yml
├── cmd/server/
│ └── main.go entrypoint, env config, server init
├── internal/
│ ├── config/
│ │ └── config.go env-var loading, validation
│ │
│ ├── crowdsec/
│ │ ├── types.go Decision, Alert, Bouncer, Machine, Hub*, Metrics structs
│ │ ├── lapi.go REST client: login, decisions CRUD, alerts, health
│ │ └── cli.go cscli wrapper: bouncers, machines, hub, metrics
│ │
│ ├── handlers/
│ │ ├── renderer.go template engine + PageData (sidebar nav)
│ │ ├── dashboard.go GET /
│ │ ├── decisions.go GET/POST /decisions, POST /decisions/delete
│ │ ├── alerts.go GET /alerts, POST /alerts/delete
│ │ ├── bouncers.go GET/POST /bouncers
│ │ ├── machines.go GET/POST /machines
│ │ ├── hub.go GET /hub, POST /hub/install, POST /hub/remove
│ │ ├── metrics.go GET /metrics-ui
│ │ └── api.go JSON API: /api/v1/stats, /api/v1/decisions, etc.
│ │
│ ├── middleware/
│ │ └── middleware.go BasicAuth, SecureHeaders, Logger, Recovery
│ │
│ └── router/
│ └── router.go route wiring
└── web/
├── templates/
│ ├── layouts/
│ │ └── base.html sidebar shell (not top-nav)
│ └── pages/
│ ├── dashboard.html
│ ├── decisions.html
│ ├── alerts.html
│ ├── bouncers.html
│ ├── machines.html
│ ├── hub.html
│ ├── metrics.html
│ └── error.html
└── static/
├── css/app.css component classes, sidebar, badges, tables
└── js/
├── app.js global: sidebar toggle, flash dismiss
├── dashboard.js SSE/polling for live stats + sparklines
└── tables.js client-side filter/sort, confirm-delete modal
```
---
## 4. Pages & Features
### 4.1 Dashboard (`/`)
- **Stat cards**: Active Bans, Alerts (24h), Bouncers connected, Machines registered
- **Live-update**: JS polls `/api/v1/stats` every N seconds, updates counters in-place
- **Recent activity**: Last 10 alerts table (scenario, IP, date, origin)
- **Recent bans**: Last 10 decisions table
- **CrowdSec version + health** badge (green/red dot)
### 4.2 Decisions (`/decisions`)
- Table: IP/Range, Type (ban/captcha), Scenario, Origin, Duration, Expires At
- **Filters**: type, origin, scope (IP / Range / Country)
- **Actions**: Delete individual (POST /decisions/delete/{id}), Bulk delete (checked rows)
- **Add Decision** form: IP, scope, type, duration (PRG pattern)
- Pagination (server-side, offset/limit passed to LAPI)
### 4.3 Alerts (`/alerts`)
- Table: ID, Scenario, IP, Country, ASN, Date, Decisions count
- Click row → detail drawer (all events in alert, full metadata)
- Delete individual alert, bulk delete selected
- Filter by scenario, IP, date range (client-side JS)
### 4.4 Bouncers (`/bouncers`)
- Table: Name, IP, Last Seen, Version, Type, Valid
- **Add** bouncer (runs `cscli bouncers add <name>`, shows generated API key once — modal)
- **Delete** bouncer (POST with confirm)
- Status badge: green (valid) / red (revoked)
- *Graceful degradation*: if cscli unavailable, show inline warning banner
### 4.5 Machines (`/machines`)
- Table: Name, IP, Last Update, Version, Auth Type, Status, Last Heartbeat
- Add machine (`cscli machines add`)
- Validate pending machine (`cscli machines validate`)
- Delete machine
- *Graceful degradation*: cscli required
### 4.6 Hub (`/hub`)
- Tabbed view: Collections | Parsers | Scenarios | Postoverflows
- Each tab: list installed (with version), list available to install
- Install / Remove actions → POST → runs `cscli hub install/remove`
- Update all button (`cscli hub update && cscli hub upgrade`)
- *Graceful degradation*: cscli required
### 4.7 Metrics (`/metrics-ui`)
- Parsed output of `cscli metrics` (acquisition, parsers, scenarios, LAPI)
- Tables grouped by category: Acquisition Sources, Parser Stats, Scenario Stats, LAPI Stats
- Auto-refresh toggle (polls every 30s)
- *Graceful degradation*: cscli required
---
## 5. Internal API (`/api/v1/...`)
Used by frontend JS — all return JSON, all protected by same BasicAuth.
| Method | Path | Description |
|---|---|---|
| GET | `/api/v1/stats` | Dashboard summary counts |
| GET | `/api/v1/decisions` | Paginated decisions (query: page, limit, type, scope) |
| DELETE | `/api/v1/decisions/{id}` | Delete one decision |
| GET | `/api/v1/alerts` | Paginated alerts |
| DELETE | `/api/v1/alerts/{id}` | Delete one alert |
| GET | `/api/v1/health` | LAPI health + cscli availability |
---
## 6. Authentication
The UI sits behind **HTTP Basic Auth** (`middleware.BasicAuth`) — simple and works in Docker behind a reverse proxy with TLS.
The app itself authenticates to CrowdSec LAPI as a **machine** (not a bouncer) to get full read+write access to decisions and alerts.
Flow:
1. On startup, `lapi.Login()` POSTs credentials to `/v1/watchers/login` → JWT
2. JWT stored in memory, refreshed on 401 response
3. All LAPI requests carry `Authorization: Bearer <jwt>`
---
## 7. UI Design
**Aesthetic**: Industrial/utilitarian dark — think terminal output meets ops dashboard. Not a generic admin panel.
- **Layout**: Fixed left sidebar (240px), collapsible on mobile. Content area with header bar.
- **Palette**: Near-black surface (`#080b10`), blue-grey panels (`#0f1520`), electric cyan accent (`#00d4ff`), threat-red (`#ff3b3b`), safe-green (`#00e676`)
- **Typography**: `JetBrains Mono` for data/numbers/badges, `IBM Plex Sans` for labels/headings
- **Tables**: Monospaced IP addresses, color-coded type badges (ban=red, captcha=amber, custom=blue)
- **Sidebar nav**: Icon + label, active state left-border accent, subtle hover
- **Stat cards**: Large mono number, label, delta indicator, thin accent top-border
- **No external chart libs**: Sparklines drawn with inline SVG `<polyline>` from JS
---
## 8. Build Phases
### Phase 1 — Foundation
- `go.mod`, config, folder structure
- `crowdsec/types.go` — all structs
- `crowdsec/lapi.go` — HTTP client, login, decisions, alerts
- `crowdsec/cli.go` — exec wrapper, JSON parsing for bouncers/machines/hub/metrics
- `middleware/middleware.go` — BasicAuth + existing middleware
- `router/router.go` skeleton
- `base.html` — sidebar shell + Tailwind config
### Phase 2 — Dashboard + API
- `handlers/api.go``/api/v1/stats`, `/api/v1/health`
- `handlers/dashboard.go` + `dashboard.html`
- `static/js/dashboard.js` — polling, counter animation, sparklines
### Phase 3 — Decisions & Alerts
- `handlers/decisions.go` + `decisions.html`
- `handlers/alerts.go` + `alerts.html`
- `static/js/tables.js` — filter, sort, bulk-select, confirm modal
### Phase 4 — Bouncers & Machines
- `handlers/bouncers.go` + `bouncers.html`
- `handlers/machines.go` + `machines.html`
- Graceful degradation UI pattern
### Phase 5 — Hub & Metrics
- `handlers/hub.go` + `hub.html`
- `handlers/metrics.go` + `metrics.html`
### Phase 6 — Docker + Polish
- `Dockerfile` (multi-stage: build → scratch/alpine)
- `docker-compose.yml` with bind-mount examples
- Error page handler
- README with setup instructions
---
## 9. Docker Compose Example
```yaml
version: "3.9"
services:
crowdsec:
image: crowdsecurity/crowdsec:latest
volumes:
- crowdsec-data:/var/lib/crowdsec/data
- crowdsec-config:/etc/crowdsec
networks:
- cs-net
crowdsec-dashy:
build: .
ports:
- "8080:8080"
environment:
CROWDSEC_API_URL: http://crowdsec:8080
CROWDSEC_API_LOGIN: crowdsec-dashy
CROWDSEC_API_PASSWORD: changeme
CSCLI_PATH: /usr/local/bin/cscli
UI_USERNAME: admin
UI_PASSWORD: changeme
volumes:
# Bind-mount cscli from the host for CLI features
- /usr/local/bin/cscli:/usr/local/bin/cscli:ro
networks:
- cs-net
depends_on:
- crowdsec
networks:
cs-net:
volumes:
crowdsec-data:
crowdsec-config:
```
---
## 10. Security Checklist
- [ ] All routes behind BasicAuth middleware
- [ ] LAPI credentials in env only, never in templates or logs
- [ ] `cscli` exec: args passed as slice (no shell injection), strict allow-list of commands
- [ ] All POST forms validate inputs server-side before exec/API call
- [ ] PRG pattern on all state-changing POSTs
- [ ] `http.MaxBytesReader` on all POST handlers
- [ ] Security headers middleware (CSP, X-Frame-Options, etc.)
- [ ] Server timeouts (Read/Write/Idle)
- [ ] Template buffer pattern (render to bytes.Buffer first)
- [ ] JWT token never logged
- [ ] Generated bouncer API keys shown exactly once, never stored by the UI
---
## 11. go.mod
```
module crowdsec-dashy
go 1.22
```
**Zero external Go dependencies.** All CrowdSec communication via stdlib `net/http` + `os/exec`.
+52
View File
@@ -0,0 +1,52 @@
# -----------------------------------------------------------------------
# Stage 1: Build
# -----------------------------------------------------------------------
FROM golang:1.22-alpine AS builder
WORKDIR /build
# Copy module files first for layer caching
COPY go.mod ./
RUN go mod download
# Copy source
COPY . .
# Build a static binary (no CGO, no external dependencies)
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
go build -ldflags="-s -w" -o crowdsec-dashy ./cmd/server
# -----------------------------------------------------------------------
# Stage 2: Minimal runtime image
# -----------------------------------------------------------------------
FROM alpine:3.19
# Install ca-certificates for HTTPS LAPI connections
RUN apk --no-cache add ca-certificates tzdata
WORKDIR /app
# Copy binary
COPY --from=builder /build/crowdsec-dashy .
# Copy web assets (templates + static)
COPY web/ ./web/
# Non-root user for security
RUN addgroup -S csui && adduser -S csui -G csui
USER csui
EXPOSE 8080
# Runtime environment — override via docker-compose or -e flags
ENV PORT=:8080 \
CROWDSEC_API_URL=http://crowdsec:8080 \
CROWDSEC_API_LOGIN= \
CROWDSEC_API_PASSWORD= \
CSCLI_PATH=/usr/local/bin/cscli \
UI_USERNAME=admin \
UI_PASSWORD=changeme \
UI_SESSION_SECRET=please-change-this-to-32-chars!! \
POLL_INTERVAL_SEC=15
ENTRYPOINT ["/app/crowdsec-dashy"]
+235
View File
@@ -0,0 +1,235 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
crowdsec-dashy
Copyright (C) 2026 nahakubuilder
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
+162
View File
@@ -0,0 +1,162 @@
# CrowdSec UI
A lightweight, dependency-free web dashboard for monitoring and managing CrowdSec.
**Stack**: Go 1.22 · `html/template` · Tailwind CSS (CDN) · Zero external Go packages
---
## Features
| Feature | Transport | Requires |
|---|---|---|
| Decisions (list, add, delete) | LAPI REST | Machine credentials |
| Alerts (list, delete) | LAPI REST | Machine credentials |
| Live dashboard stats | LAPI REST (polled) | Machine credentials |
| Bouncers (list, add, delete) | `cscli exec` | cscli binary |
| Machines (list, validate, delete) | `cscli exec` | cscli binary |
| Hub (collections/parsers/scenarios) | `cscli exec` | cscli binary |
| Metrics | `cscli exec` | cscli binary |
> All `cscli`-backed features degrade gracefully with a banner if the binary is unavailable.
---
## Quick Start
### 1. Register the UI as a CrowdSec machine
```bash
# On the host running CrowdSec:
sudo cscli machines add crowdsec-dashy --password your-password -a
# Or if CrowdSec is in Docker:
docker exec crowdsec cscli machines add crowdsec-dashy --password your-password -a
```
### 2. Configure environment variables
Copy or edit `docker-compose.yml` and set:
```yaml
CROWDSEC_API_LOGIN: "crowdsec-dashy"
CROWDSEC_API_PASSWORD: "your-password" # must match step 1
UI_USERNAME: "admin"
UI_PASSWORD: "your-ui-password" # Basic Auth for the web UI
UI_SESSION_SECRET: "32-char-random-string"
```
### 3. Set up cscli bind-mount (for CLI features)
```bash
# If CrowdSec is in Docker, extract cscli:
docker cp crowdsec:/usr/local/bin/cscli /usr/local/bin/cscli
chmod +x /usr/local/bin/cscli
# The docker-compose.yml already bind-mounts it:
# - /usr/local/bin/cscli:/usr/local/bin/cscli:ro
```
### 4. Launch
```bash
docker compose up -d
```
Open `http://localhost:8080` — browser will prompt for Basic Auth.
---
## Running Directly (no Docker)
```bash
# Build
go build -o crowdsec-dashy ./cmd/server
# Set env vars
export CROWDSEC_API_URL="http://localhost:8080"
export CROWDSEC_API_LOGIN="crowdsec-dashy"
export CROWDSEC_API_PASSWORD="your-password"
export UI_USERNAME="admin"
export UI_PASSWORD="your-ui-password"
export UI_SESSION_SECRET="32-char-random-string"
# Run
./crowdsec-dashy
```
---
## Environment Variables
| Variable | Default | Description |
|---|---|---|
| `PORT` | `:8080` | Listen address |
| `CROWDSEC_API_URL` | `http://localhost:8080` | CrowdSec LAPI base URL |
| `CROWDSEC_API_LOGIN` | *(required)* | Machine login (cscli machines add) |
| `CROWDSEC_API_PASSWORD` | *(required)* | Machine password |
| `CSCLI_PATH` | `/usr/local/bin/cscli` | Path to cscli binary |
| `UI_USERNAME` | `admin` | Basic Auth username |
| `UI_PASSWORD` | `changeme` | Basic Auth password — **change this** |
| `UI_SESSION_SECRET` | *(required, ≥32 chars)* | HMAC signing key |
| `POLL_INTERVAL_SEC` | `15` | Dashboard live-poll interval |
---
## Project Structure
```
crowdsec-dashy/
├── cmd/server/main.go entrypoint
├── internal/
│ ├── config/config.go env-var loading
│ ├── crowdsec/
│ │ ├── types.go all shared structs
│ │ ├── lapi.go REST client (decisions, alerts)
│ │ └── cli.go cscli exec wrapper
│ ├── handlers/
│ │ ├── renderer.go template engine + PageData
│ │ ├── dashboard.go
│ │ ├── decisions.go
│ │ ├── alerts.go
│ │ ├── bouncers.go
│ │ ├── machines.go
│ │ ├── hub.go
│ │ ├── metrics.go
│ │ └── api.go JSON API for dashboard polling
│ ├── middleware/middleware.go BasicAuth, Logger, SecureHeaders, Recovery
│ └── router/router.go route wiring
└── web/
├── templates/layouts/base.html sidebar shell
├── templates/pages/ one file per page
└── static/css/app.css all component styles
static/js/app.js global JS
static/js/dashboard.js stats polling
```
---
## Adding a New Page
1. Create `internal/handlers/mypage.go` with a handler struct
2. Create `web/templates/pages/mypage.html` starting with `{{template "base" .}}`
3. Add to `SidebarNav` in `renderer.go`
4. Add `mux.Handle("/mypage", handlers.NewMyPageHandler(deps))` in `router.go`
---
## Security Notes
- All routes protected by HTTP Basic Auth — put behind TLS (nginx/Caddy) in production
- `cscli` args passed as a slice (never through a shell); strict allow-list of subcommands
- LAPI JWT stored in memory only, never logged
- Generated bouncer API keys shown exactly once, never stored by the UI
- Security headers on every response: CSP, X-Frame-Options, X-Content-Type-Options
- Server has explicit Read/Write/Idle timeouts
---
## Dependencies
**Go**: zero external packages — stdlib only.
**Frontend**: Tailwind CSS via CDN (CSS only, no JS framework), Google Fonts via CDN.
+80
View File
@@ -0,0 +1,80 @@
package main
import (
"context"
"log"
"net/http"
"os"
"path/filepath"
"time"
"crowdsec-dashy/internal/config"
"crowdsec-dashy/internal/crowdsec"
"crowdsec-dashy/internal/router"
)
func main() {
// ----------------------------------------------------------------
// Configuration
// ----------------------------------------------------------------
cfg, err := config.Load()
if err != nil {
log.Fatalf("configuration error: %v", err)
}
// Resolve paths
cwd, err := os.Getwd()
if err != nil {
log.Fatalf("cannot determine working directory: %v", err)
}
staticDir := filepath.Join(cwd, "web", "static")
templateDir := filepath.Join(cwd, "web", "templates")
// ----------------------------------------------------------------
// CrowdSec LAPI — authenticate at startup
// ----------------------------------------------------------------
lapi := crowdsec.NewLAPIClient(cfg.CrowdSecAPIURL, cfg.CrowdSecAPILogin, cfg.CrowdSecAPIPassword)
log.Printf("connecting to CrowdSec LAPI at %s ...", cfg.CrowdSecAPIURL)
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
if err := lapi.Login(ctx); err != nil {
cancel()
log.Fatalf("failed to authenticate with CrowdSec LAPI: %v\n"+
"Ensure CROWDSEC_API_LOGIN and CROWDSEC_API_PASSWORD are correct and\n"+
"the machine is registered: cscli machines add %s -a", err, cfg.CrowdSecAPILogin)
}
cancel()
log.Println("authenticated with CrowdSec LAPI")
// CLI availability
if cfg.CscliAvailable() {
log.Printf("cscli available at %s", cfg.CscliPath)
} else {
log.Printf("[WARN] cscli not found at %s — bouncer/machine/hub/metrics features disabled", cfg.CscliPath)
}
// ----------------------------------------------------------------
// Build router
// ----------------------------------------------------------------
handler, err := router.New(cfg, staticDir, templateDir)
if err != nil {
log.Fatalf("failed to initialise router: %v", err)
}
// ----------------------------------------------------------------
// HTTP server
// ----------------------------------------------------------------
srv := &http.Server{
Addr: cfg.Port,
Handler: handler,
ReadTimeout: 10 * time.Second,
WriteTimeout: 60 * time.Second, // longer for hub operations
IdleTimeout: 120 * time.Second,
}
log.Printf("CrowdSec UI listening on %s", srv.Addr)
log.Printf("UI credentials: %s / [redacted]", cfg.UIUsername)
if err := srv.ListenAndServe(); err != nil {
log.Fatalf("server error: %v", err)
}
}
+68
View File
@@ -0,0 +1,68 @@
# -----------------------------------------------------------------------
# CrowdSec Dashy — Docker Compose
#
# Prerequisites:
# 1. Register the UI as a CrowdSec machine BEFORE starting this stack:
# docker exec crowdsec cscli machines add crowdsec-dashy --password changeme -a
#
# 2. Edit the environment variables below (especially passwords).
#
# cscli bind-mount:
# The UI needs the cscli binary for bouncer/machine/hub/metrics management.
# If CrowdSec is running in Docker, extract the binary from the image:
# docker cp crowdsec:/usr/local/bin/cscli /usr/local/bin/cscli
# Then the bind-mount below works automatically.
#
# If cscli is NOT available, those sections will show a degradation banner
# and all LAPI-based features (decisions, alerts) continue to work normally.
# -----------------------------------------------------------------------
services:
crowdsec:
image: crowdsecurity/crowdsec:latest
container_name: crowdsec
restart: unless-stopped
environment:
GID: "1000"
COLLECTIONS: "crowdsecurity/linux crowdsecurity/nginx"
volumes:
- crowdsec-db:/var/lib/crowdsec/data
- crowdsec-config:/etc/crowdsec
- /var/log:/var/log:ro
networks:
- cs-internal
crowdsec-dashy:
build: .
# Or use a published image:
# image: ghcr.io/your-org/crowdsec-dashy:latest
container_name: crowdsec-dashy
restart: unless-stopped
ports:
- "8080:8080"
environment:
PORT: ":8080"
CROWDSEC_API_URL: "http://crowdsec:8080"
CROWDSEC_API_LOGIN: "crowdsec-dashy" # match what you registered above
CROWDSEC_API_PASSWORD: "changeme" # CHANGE THIS
CSCLI_PATH: "/usr/local/bin/cscli"
UI_USERNAME: "admin" # UI Basic Auth login
UI_PASSWORD: "changeme" # CHANGE THIS
UI_SESSION_SECRET: "replace-with-32-random-chars-here" # CHANGE THIS
POLL_INTERVAL_SEC: "15"
volumes:
# Bind-mount cscli binary from host (or from crowdsec container)
# See setup instructions above
- /usr/local/bin/cscli:/usr/local/bin/cscli:ro
networks:
- cs-internal
depends_on:
- crowdsec
networks:
cs-internal:
driver: bridge
volumes:
crowdsec-db:
crowdsec-config:
+3
View File
@@ -0,0 +1,3 @@
module crowdsec-dashy
go 1.26.2
+405
View File
@@ -0,0 +1,405 @@
package crowdsec
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"os/exec"
"regexp"
"strings"
"time"
)
// CLIClient wraps the cscli binary.
type CLIClient struct {
cscliPath string
}
// NewCLIClient creates a new CLI client.
// cscliPath should be the absolute path to the cscli binary.
func NewCLIClient(cscliPath string) *CLIClient {
return &CLIClient{cscliPath: cscliPath}
}
// -----------------------------------------------------------------------
// Bouncers
// -----------------------------------------------------------------------
// ListBouncers returns all registered bouncers.
func (c *CLIClient) ListBouncers(ctx context.Context) ([]Bouncer, error) {
out, err := c.run(ctx, "bouncers", "list", "-o", "json")
if err != nil {
return nil, err
}
var bouncers []Bouncer
if err := json.Unmarshal(out, &bouncers); err != nil {
return nil, fmt.Errorf("parse bouncers: %w\noutput: %s", err, string(out))
}
return bouncers, nil
}
// AddBouncer registers a new bouncer and returns the generated API key.
func (c *CLIClient) AddBouncer(ctx context.Context, name string) (*AddBouncerResult, error) {
if err := validateName(name); err != nil {
return nil, err
}
// cscli bouncers add <name> -o raw → prints only the API key
out, err := c.run(ctx, "bouncers", "add", name, "-o", "raw")
if err != nil {
return nil, err
}
apiKey := strings.TrimSpace(string(out))
if apiKey == "" {
return nil, fmt.Errorf("no API key returned for bouncer %q", name)
}
return &AddBouncerResult{Name: name, APIKey: apiKey}, nil
}
// DeleteBouncer removes a bouncer by name.
func (c *CLIClient) DeleteBouncer(ctx context.Context, name string) error {
if err := validateName(name); err != nil {
return err
}
_, err := c.run(ctx, "bouncers", "delete", name)
return err
}
// -----------------------------------------------------------------------
// Machines
// -----------------------------------------------------------------------
// ListMachines returns all registered machines.
func (c *CLIClient) ListMachines(ctx context.Context) ([]Machine, error) {
out, err := c.run(ctx, "machines", "list", "-o", "json")
if err != nil {
return nil, err
}
var machines []Machine
if err := json.Unmarshal(out, &machines); err != nil {
return nil, fmt.Errorf("parse machines: %w\noutput: %s", err, string(out))
}
return machines, nil
}
// DeleteMachine removes a machine by ID.
func (c *CLIClient) DeleteMachine(ctx context.Context, machineID string) error {
if err := validateName(machineID); err != nil {
return err
}
_, err := c.run(ctx, "machines", "delete", "--machine-id", machineID)
return err
}
// ValidateMachine validates a pending machine registration.
func (c *CLIClient) ValidateMachine(ctx context.Context, machineID string) error {
if err := validateName(machineID); err != nil {
return err
}
_, err := c.run(ctx, "machines", "validate", machineID)
return err
}
// -----------------------------------------------------------------------
// Hub — Collections
// -----------------------------------------------------------------------
// ListCollections returns all known collections.
func (c *CLIClient) ListCollections(ctx context.Context) ([]HubItem, error) {
return c.listHubItems(ctx, "collections")
}
// InstallCollection installs a hub collection.
func (c *CLIClient) InstallCollection(ctx context.Context, name string) error {
return c.hubAction(ctx, "collections", "install", name)
}
// RemoveCollection removes a hub collection.
func (c *CLIClient) RemoveCollection(ctx context.Context, name string) error {
return c.hubAction(ctx, "collections", "remove", name)
}
// -----------------------------------------------------------------------
// Hub — Parsers
// -----------------------------------------------------------------------
// ListParsers returns all known parsers.
func (c *CLIClient) ListParsers(ctx context.Context) ([]HubItem, error) {
return c.listHubItems(ctx, "parsers")
}
// InstallParser installs a parser.
func (c *CLIClient) InstallParser(ctx context.Context, name string) error {
return c.hubAction(ctx, "parsers", "install", name)
}
// RemoveParser removes a parser.
func (c *CLIClient) RemoveParser(ctx context.Context, name string) error {
return c.hubAction(ctx, "parsers", "remove", name)
}
// -----------------------------------------------------------------------
// Hub — Scenarios
// -----------------------------------------------------------------------
// ListScenarios returns all known scenarios.
func (c *CLIClient) ListScenarios(ctx context.Context) ([]HubItem, error) {
return c.listHubItems(ctx, "scenarios")
}
// InstallScenario installs a scenario.
func (c *CLIClient) InstallScenario(ctx context.Context, name string) error {
return c.hubAction(ctx, "scenarios", "install", name)
}
// RemoveScenario removes a scenario.
func (c *CLIClient) RemoveScenario(ctx context.Context, name string) error {
return c.hubAction(ctx, "scenarios", "remove", name)
}
// -----------------------------------------------------------------------
// Hub — Postoverflows
// -----------------------------------------------------------------------
// ListPostoverflows returns all known postoverflows.
func (c *CLIClient) ListPostoverflows(ctx context.Context) ([]HubItem, error) {
return c.listHubItems(ctx, "postoverflows")
}
// HubUpdate runs cscli hub update && cscli hub upgrade.
func (c *CLIClient) HubUpdate(ctx context.Context) error {
if _, err := c.run(ctx, "hub", "update"); err != nil {
return fmt.Errorf("hub update: %w", err)
}
if _, err := c.run(ctx, "hub", "upgrade"); err != nil {
return fmt.Errorf("hub upgrade: %w", err)
}
return nil
}
// -----------------------------------------------------------------------
// Metrics
// -----------------------------------------------------------------------
// GetMetrics runs cscli metrics and returns parsed sections.
func (c *CLIClient) GetMetrics(ctx context.Context) ([]MetricsSection, error) {
// cscli metrics does not support JSON output reliably — parse table output
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
out, err := c.run(ctx, "metrics")
if err != nil {
return nil, err
}
return parseMetricsOutput(string(out)), nil
}
// GetVersion returns cscli version information.
func (c *CLIClient) GetVersion(ctx context.Context) (string, error) {
out, err := c.run(ctx, "version")
if err != nil {
return "", err
}
// version output is plain text like "v1.6.4-..."
return strings.TrimSpace(string(out)), nil
}
// -----------------------------------------------------------------------
// Internal helpers
// -----------------------------------------------------------------------
// run executes cscli with the given arguments.
// Arguments are passed as a slice — never through a shell — preventing injection.
// Only specific subcommands are allowed.
func (c *CLIClient) run(ctx context.Context, args ...string) ([]byte, error) {
if err := validateArgs(args); err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, c.cscliPath, args...) //nolint:gosec — path validated at startup
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("cscli %s: %w — %s", strings.Join(args, " "), err, stderr.String())
}
return stdout.Bytes(), nil
}
// allowedSubcommands is the strict allow-list of cscli first arguments.
var allowedSubcommands = map[string]bool{
"bouncers": true,
"machines": true,
"collections": true,
"parsers": true,
"scenarios": true,
"postoverflows": true,
"hub": true,
"metrics": true,
"version": true,
}
// allowedActions for each subcommand.
var allowedActions = map[string]bool{
"list": true,
"add": true,
"delete": true,
"install": true,
"remove": true,
"update": true,
"upgrade": true,
"validate": true,
}
// safeArg matches strings that are safe to pass as arguments (no shell metacharacters).
var safeArg = regexp.MustCompile(`^[a-zA-Z0-9_./:@\-]+$`)
func validateArgs(args []string) error {
if len(args) == 0 {
return fmt.Errorf("no subcommand provided")
}
if !allowedSubcommands[args[0]] {
return fmt.Errorf("disallowed cscli subcommand: %q", args[0])
}
// Skip flag-value pairs like "-o json" and "--machine-id <id>" — validate values
for i := 1; i < len(args); i++ {
arg := args[i]
if strings.HasPrefix(arg, "-") {
continue // flags are fine
}
if allowedActions[arg] {
continue // known action words
}
if arg == "raw" || arg == "json" || arg == "human" {
continue // output format values
}
// Everything else (names, IDs) must match safe pattern
if !safeArg.MatchString(arg) {
return fmt.Errorf("unsafe cscli argument: %q", arg)
}
}
return nil
}
// validateName checks that a name passed by the user is safe to use as a cscli argument.
var validName = regexp.MustCompile(`^[a-zA-Z0-9_\-]{1,64}$`)
func validateName(name string) error {
if !validName.MatchString(name) {
return fmt.Errorf("invalid name %q: must be 1-64 alphanumeric/dash/underscore characters", name)
}
return nil
}
func (c *CLIClient) listHubItems(ctx context.Context, kind string) ([]HubItem, error) {
out, err := c.run(ctx, kind, "list", "-o", "json")
if err != nil {
return nil, err
}
// cscli returns either {"<kind>": [...]} or just [...]
// Try array first
var items []HubItem
if err := json.Unmarshal(out, &items); err == nil {
return items, nil
}
// Try object wrapper
var wrapper map[string][]HubItem
if err := json.Unmarshal(out, &wrapper); err != nil {
return nil, fmt.Errorf("parse %s: %w\noutput: %s", kind, err, string(out))
}
for _, v := range wrapper {
return v, nil
}
return []HubItem{}, nil
}
func (c *CLIClient) hubAction(ctx context.Context, kind, action, name string) error {
if err := validateName(name); err != nil {
return err
}
_, err := c.run(ctx, kind, action, name)
return err
}
// parseMetricsOutput parses the tabular output of `cscli metrics`.
// It looks for lines that look like table headers (─── separators).
func parseMetricsOutput(output string) []MetricsSection {
var sections []MetricsSection
var current *MetricsSection
var headerFound bool
scanner := bufio.NewScanner(strings.NewReader(output))
for scanner.Scan() {
line := scanner.Text()
// Section title lines — plain text before the table
if !strings.Contains(line, "│") && !strings.Contains(line, "─") &&
strings.TrimSpace(line) != "" && !strings.HasPrefix(strings.TrimSpace(line), "time=") {
if current != nil && len(current.Rows) > 0 {
sections = append(sections, *current)
}
current = &MetricsSection{Title: strings.TrimSpace(line)}
headerFound = false
continue
}
if current == nil {
continue
}
// Header row (contains │ and no numbers)
if strings.Contains(line, "│") && !headerFound {
parts := splitTableRow(line)
if len(parts) > 0 {
current.Headers = parts
headerFound = true
}
continue
}
// Separator lines
if strings.Contains(line, "─") {
continue
}
// Data rows
if strings.Contains(line, "│") && headerFound {
parts := splitTableRow(line)
if len(parts) > 0 {
current.Rows = append(current.Rows, parts)
}
}
}
if current != nil && len(current.Rows) > 0 {
sections = append(sections, *current)
}
return sections
}
func splitTableRow(line string) []string {
parts := strings.Split(line, "│")
var cells []string
for _, p := range parts {
trimmed := strings.TrimSpace(p)
if trimmed != "" {
cells = append(cells, trimmed)
}
}
return cells
}
+337
View File
@@ -0,0 +1,337 @@
package crowdsec
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"sync"
"time"
)
// LAPIClient is a thread-safe HTTP client for the CrowdSec Local API.
type LAPIClient struct {
baseURL string
login string
password string
mu sync.RWMutex
token string // JWT, refreshed on 401
http *http.Client
}
// NewLAPIClient creates a new client. Call Login() before other methods.
func NewLAPIClient(baseURL, login, password string) *LAPIClient {
return &LAPIClient{
baseURL: baseURL,
login: login,
password: password,
http: &http.Client{
Timeout: 15 * time.Second,
},
}
}
// Login authenticates with the LAPI and stores the JWT token.
func (c *LAPIClient) Login(ctx context.Context) error {
payload := LoginRequest{
MachineID: c.login,
Password: c.password,
}
body, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("lapi login marshal: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
c.baseURL+"/v1/watchers/login", bytes.NewReader(body))
if err != nil {
return fmt.Errorf("lapi login request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.http.Do(req)
if err != nil {
return fmt.Errorf("lapi login: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
data, _ := io.ReadAll(resp.Body)
return fmt.Errorf("lapi login: status %d: %s", resp.StatusCode, string(data))
}
var lr LoginResponse
if err := json.NewDecoder(resp.Body).Decode(&lr); err != nil {
return fmt.Errorf("lapi login decode: %w", err)
}
c.mu.Lock()
c.token = lr.Token
c.mu.Unlock()
return nil
}
// IsHealthy returns true if the LAPI responds to a ping.
func (c *LAPIClient) IsHealthy(ctx context.Context) bool {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+"/v1/decisions", nil)
if err != nil {
return false
}
c.setAuth(req)
req.URL.RawQuery = "limit=1"
resp, err := c.http.Do(req)
if err != nil {
return false
}
resp.Body.Close()
return resp.StatusCode < 500
}
// -----------------------------------------------------------------------
// Decisions
// -----------------------------------------------------------------------
// DecisionFilter contains optional filters for listing decisions.
type DecisionFilter struct {
Limit int
Offset int
Type string // ban, captcha, etc.
Scope string // Ip, Range, Country
Value string // specific IP/value
Origin string
}
// ListDecisions returns decisions matching the filter.
func (c *LAPIClient) ListDecisions(ctx context.Context, f DecisionFilter) ([]Decision, error) {
q := url.Values{}
q.Set("limit", strconv.Itoa(max(f.Limit, 100)))
if f.Offset > 0 {
q.Set("offset", strconv.Itoa(f.Offset))
}
if f.Type != "" {
q.Set("type", f.Type)
}
if f.Scope != "" {
q.Set("scope", f.Scope)
}
if f.Value != "" {
q.Set("value", f.Value)
}
if f.Origin != "" {
q.Set("origin", f.Origin)
}
var decisions []Decision
err := c.doJSON(ctx, http.MethodGet, "/v1/decisions?"+q.Encode(), nil, &decisions)
if err != nil {
return nil, err
}
if decisions == nil {
decisions = []Decision{}
}
return decisions, nil
}
// DeleteDecision deletes a decision by ID.
func (c *LAPIClient) DeleteDecision(ctx context.Context, id int64) error {
return c.doJSON(ctx, http.MethodDelete,
fmt.Sprintf("/v1/decisions/%d", id), nil, nil)
}
// DeleteAllDecisions deletes all active decisions.
func (c *LAPIClient) DeleteAllDecisions(ctx context.Context) error {
return c.doJSON(ctx, http.MethodDelete, "/v1/decisions", nil, nil)
}
// AddDecision posts one manual decision to the LAPI.
func (c *LAPIClient) AddDecision(ctx context.Context, d DecisionInput) error {
payload := struct {
Decisions []DecisionInput `json:"decisions"`
}{
Decisions: []DecisionInput{d},
}
// The LAPI wraps decisions in an alert object
type alertPayload struct {
Capacity int32 `json:"capacity"`
Decisions []DecisionInput `json:"decisions"`
Events []interface{} `json:"events"`
EventsCount int32 `json:"events_count"`
Leakspeed string `json:"leakspeed"`
Message string `json:"message"`
ScenarioHash string `json:"scenario_hash"`
ScenarioVersion string `json:"scenario_version"`
Simulated bool `json:"simulated"`
Source AlertSource `json:"source"`
StartAt string `json:"start_at"`
StopAt string `json:"stop_at"`
}
now := time.Now().UTC().Format(time.RFC3339)
ap := alertPayload{
Capacity: 0,
Decisions: payload.Decisions,
Events: []interface{}{},
EventsCount: 1,
Leakspeed: "0",
Message: fmt.Sprintf("manual decision for %s", d.Value),
Simulated: false,
Source: AlertSource{
Scope: d.Scope,
Value: d.Value,
IP: d.Value,
},
StartAt: now,
StopAt: now,
}
return c.doJSON(ctx, http.MethodPost, "/v1/alerts", []alertPayload{ap}, nil)
}
// -----------------------------------------------------------------------
// Alerts
// -----------------------------------------------------------------------
// AlertFilter contains optional filters for listing alerts.
type AlertFilter struct {
Limit int
Offset int
Scenario string
IP string
Since string // duration string e.g. "24h"
}
// ListAlerts returns alerts matching the filter.
func (c *LAPIClient) ListAlerts(ctx context.Context, f AlertFilter) ([]Alert, error) {
q := url.Values{}
q.Set("limit", strconv.Itoa(max(f.Limit, 100)))
if f.Offset > 0 {
q.Set("offset", strconv.Itoa(f.Offset))
}
if f.Scenario != "" {
q.Set("scenario", f.Scenario)
}
if f.IP != "" {
q.Set("ip", f.IP)
}
if f.Since != "" {
q.Set("since", f.Since)
}
var alerts []Alert
err := c.doJSON(ctx, http.MethodGet, "/v1/alerts?"+q.Encode(), nil, &alerts)
if err != nil {
return nil, err
}
if alerts == nil {
alerts = []Alert{}
}
return alerts, nil
}
// DeleteAlert deletes an alert by ID.
func (c *LAPIClient) DeleteAlert(ctx context.Context, id int64) error {
return c.doJSON(ctx, http.MethodDelete,
fmt.Sprintf("/v1/alerts/%d", id), nil, nil)
}
// -----------------------------------------------------------------------
// Internal helpers
// -----------------------------------------------------------------------
// doJSON performs an authenticated JSON request, automatically re-logging on 401.
func (c *LAPIClient) doJSON(ctx context.Context, method, path string, reqBody, respBody any) error {
err := c.doJSONOnce(ctx, method, path, reqBody, respBody)
if err == nil {
return nil
}
// If 401, try refreshing token once
if isUnauthorized(err) {
if loginErr := c.Login(ctx); loginErr != nil {
return fmt.Errorf("lapi re-login failed: %w", loginErr)
}
return c.doJSONOnce(ctx, method, path, reqBody, respBody)
}
return err
}
type lapiError struct {
status int
body string
}
func (e *lapiError) Error() string {
return fmt.Sprintf("lapi status %d: %s", e.status, e.body)
}
func isUnauthorized(err error) bool {
if e, ok := err.(*lapiError); ok {
return e.status == http.StatusUnauthorized
}
return false
}
func (c *LAPIClient) doJSONOnce(ctx context.Context, method, path string, reqBody, respBody any) error {
var bodyReader io.Reader
if reqBody != nil {
b, err := json.Marshal(reqBody)
if err != nil {
return fmt.Errorf("marshal request: %w", err)
}
bodyReader = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, bodyReader)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
c.setAuth(req)
resp, err := c.http.Do(req)
if err != nil {
return fmt.Errorf("lapi %s %s: %w", method, path, err)
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("lapi read body: %w", err)
}
if resp.StatusCode >= 400 {
return &lapiError{status: resp.StatusCode, body: string(data)}
}
if respBody != nil && len(data) > 0 && string(data) != "null" {
if err := json.Unmarshal(data, respBody); err != nil {
return fmt.Errorf("lapi decode response: %w", err)
}
}
return nil
}
func (c *LAPIClient) setAuth(r *http.Request) {
c.mu.RLock()
token := c.token
c.mu.RUnlock()
if token != "" {
r.Header.Set("Authorization", "Bearer "+token)
}
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
+252
View File
@@ -0,0 +1,252 @@
// Package handlers provides the template renderer and all HTTP handlers.
package handlers
import (
"bytes"
"fmt"
"html/template"
"log"
"net/http"
"path/filepath"
"strings"
"crowdsec-dashy/internal/crowdsec"
)
// -----------------------------------------------------------------------
// Renderer
// -----------------------------------------------------------------------
// Renderer holds pre-parsed templates, one per page.
type Renderer struct {
templates map[string]*template.Template
funcMap template.FuncMap
}
// NewRenderer parses all page templates against the base layout.
func NewRenderer(templateDir string) (*Renderer, error) {
r := &Renderer{
templates: make(map[string]*template.Template),
funcMap: buildFuncMap(),
}
basePath := filepath.Join(templateDir, "layouts", "base.html")
pages, err := filepath.Glob(filepath.Join(templateDir, "pages", "*.html"))
if err != nil {
return nil, fmt.Errorf("renderer: glob pages: %w", err)
}
if len(pages) == 0 {
return nil, fmt.Errorf("renderer: no page templates found in %s/pages/", templateDir)
}
for _, page := range pages {
name := templateName(page)
tmpl, err := template.New("base").
Funcs(r.funcMap).
ParseFiles(basePath, page)
if err != nil {
return nil, fmt.Errorf("renderer: parse %s: %w", name, err)
}
r.templates[name] = tmpl
log.Printf("renderer: registered template %q", name)
}
return r, nil
}
// Render executes the named template into a buffer then writes to w.
func (r *Renderer) Render(w http.ResponseWriter, name string, data any) {
tmpl, ok := r.templates[name]
if !ok {
http.Error(w, fmt.Sprintf("template %q not found", name), http.StatusInternalServerError)
return
}
var buf bytes.Buffer
if err := tmpl.ExecuteTemplate(&buf, "base", data); err != nil {
log.Printf("renderer: execute %q: %v", name, err)
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = buf.WriteTo(w)
}
// RenderError renders the error page.
func (r *Renderer) RenderError(w http.ResponseWriter, code int, msg string) {
w.WriteHeader(code)
r.Render(w, "error", ErrorData{
PageData: PageData{CurrentPath: "/error", Title: fmt.Sprintf("Error %d", code)},
Code: code,
Message: msg,
})
}
func templateName(path string) string {
base := filepath.Base(path)
return base[:len(base)-len(filepath.Ext(base))]
}
// -----------------------------------------------------------------------
// FuncMap
// -----------------------------------------------------------------------
func buildFuncMap() template.FuncMap {
return template.FuncMap{
"inc": func(i int) int { return i + 1 },
"dec": func(i int) int { return i - 1 },
// dict builds a map for passing multiple values to a sub-template.
// Usage: {{template "foo" dict "Key1" val1 "Key2" val2}}
"dict": func(pairs ...any) (map[string]any, error) {
if len(pairs)%2 != 0 {
return nil, fmt.Errorf("dict: odd number of arguments")
}
m := make(map[string]any, len(pairs)/2)
for i := 0; i < len(pairs); i += 2 {
k, ok := pairs[i].(string)
if !ok {
return nil, fmt.Errorf("dict: key %v is not a string", pairs[i])
}
m[k] = pairs[i+1]
}
return m, nil
},
// decisionTypeBadge returns a CSS class suffix for a decision type.
"decisionBadgeClass": func(t string) string {
switch strings.ToLower(t) {
case "ban":
return "badge-red"
case "captcha":
return "badge-amber"
case "throttle":
return "badge-blue"
default:
return "badge-gray"
}
},
// originBadgeClass returns a CSS class for a decision origin.
"originBadgeClass": func(o string) string {
switch strings.ToLower(o) {
case "crowdsec":
return "badge-cyan"
case "cscli":
return "badge-purple"
case "lists":
return "badge-green"
default:
return "badge-gray"
}
},
// hubStatusClass returns a CSS class for a hub item status.
"hubStatusClass": func(s string) string {
switch strings.ToLower(s) {
case "enabled":
return "badge-green"
case "disabled":
return "badge-gray"
case "update-available":
return "badge-amber"
default:
return "badge-gray"
}
},
// safeHTML allows raw HTML in templates (use carefully).
"safeHTML": func(s string) template.HTML {
return template.HTML(s) //nolint:gosec
},
// boolIcon returns a UTF-8 icon for boolean display.
"boolIcon": func(b bool) string {
if b {
return "✓"
}
return "✗"
},
// truncate shortens a string.
"truncate": func(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "…"
},
// join joins a string slice.
"join": strings.Join,
}
}
// -----------------------------------------------------------------------
// Shared page data
// -----------------------------------------------------------------------
// NavItem describes one sidebar navigation entry.
type NavItem struct {
Path string
Label string
Icon string
Divider bool // show divider before this item
}
// SidebarNav returns the full navigation definition.
var SidebarNav = []NavItem{
{Path: "/", Label: "Dashboard", Icon: `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>`},
{Path: "/decisions", Label: "Decisions", Icon: `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>`, Divider: false},
{Path: "/alerts", Label: "Alerts", Icon: `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>`},
{Path: "/bouncers", Label: "Bouncers", Icon: `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>`, Divider: true},
{Path: "/machines", Label: "Machines", Icon: `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="8" rx="2" ry="2"/><rect x="2" y="14" width="20" height="8" rx="2" ry="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/></svg>`},
{Path: "/hub", Label: "Hub", Icon: `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>`, Divider: true},
{Path: "/metrics-ui", Label: "Metrics", Icon: `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>`},
}
// PageData contains fields available to every template.
type PageData struct {
CurrentPath string
Title string
Nav []NavItem
Flash FlashMessage
CLIAvailable bool
PollInterval int
}
// FlashMessage is a one-shot notification shown on the next page load.
type FlashMessage struct {
Type string // success, error, warning, info
Message string
}
// ErrorData is passed to the error page template.
type ErrorData struct {
PageData
Code int
Message string
}
// NewPageData creates PageData from the current request.
func NewPageData(r *http.Request, title string, cliAvail bool, pollSec int) PageData {
return PageData{
CurrentPath: r.URL.Path,
Title: title,
Nav: SidebarNav,
CLIAvailable: cliAvail,
PollInterval: pollSec,
}
}
// WithFlash attaches a flash message to PageData.
func (pd PageData) WithFlash(flashType, msg string) PageData {
pd.Flash = FlashMessage{Type: flashType, Message: msg}
return pd
}
// -----------------------------------------------------------------------
// Shared handler dependencies
// -----------------------------------------------------------------------
// Deps holds shared dependencies injected into every handler.
type Deps struct {
Renderer *Renderer
LAPI *crowdsec.LAPIClient
CLI *crowdsec.CLIClient
CLIAvailable bool
PollInterval int
}
+693
View File
@@ -0,0 +1,693 @@
/* =============================================================
CrowdSec UI — Industrial Dark Dashboard
Palette: near-black surfaces · electric cyan accent · threat-red · safe-green
Fonts: JetBrains Mono (data) · IBM Plex Sans (UI)
============================================================= */
/* ---------------------------------------------------------------
CSS Variables
--------------------------------------------------------------- */
:root {
--s-950: #04070d;
--s-900: #080b10;
--s-800: #0d1117;
--s-700: #111823;
--s-600: #182030;
--s-500: #1e2a3f;
--accent: #00d4ff;
--accent-dim: #0099bb;
--threat: #ff3b3b;
--threat-dim: #cc2222;
--safe: #00e676;
--safe-dim: #00a854;
--warn: #ffb300;
--warn-dim: #cc8800;
--muted: #4a5568;
--border: rgba(255,255,255,0.06);
--sidebar-w: 240px;
}
/* ---------------------------------------------------------------
Global reset & base
--------------------------------------------------------------- */
*, *::before, *::after { box-sizing: border-box; }
html, body { height: 100%; margin: 0; }
body {
background: var(--s-950);
color: #c9d1d9;
font-family: 'IBM Plex Sans', system-ui, sans-serif;
font-size: 14px;
line-height: 1.6;
}
/* Scrollbar */
::-webkit-scrollbar { width: 5px; height: 5px; }
::-webkit-scrollbar-track { background: var(--s-950); }
::-webkit-scrollbar-thumb { background: var(--s-600); border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: var(--accent-dim); }
/* ---------------------------------------------------------------
Sidebar
--------------------------------------------------------------- */
.sidebar {
width: var(--sidebar-w);
min-width: var(--sidebar-w);
height: 100vh;
background: var(--s-900);
border-right: 1px solid var(--border);
display: flex;
flex-direction: column;
overflow: hidden;
flex-shrink: 0;
z-index: 100;
transition: transform 0.25s ease;
}
.sidebar-logo {
display: flex;
align-items: center;
gap: 10px;
padding: 20px 16px 16px;
border-bottom: 1px solid var(--border);
margin-bottom: 20px;
}
.logo-icon {
width: 32px;
height: 32px;
background: rgba(0,212,255,0.08);
border: 1px solid rgba(0,212,255,0.2);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.logo-name {
display: block;
font-family: 'JetBrains Mono', monospace;
font-weight: 600;
font-size: 13px;
color: #e6edf3;
line-height: 1.2;
}
.logo-sub {
display: block;
font-size: 10px;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.06em;
}
/* Nav */
.sidebar-nav {
flex: 1;
overflow-y: auto;
padding: 0 8px;
}
.nav-item {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 12px;
border-radius: 6px;
color: #6e7681;
text-decoration: none;
font-size: 13px;
font-weight: 500;
transition: color 0.15s, background 0.15s;
margin-bottom: 2px;
border-left: 2px solid transparent;
}
.nav-item:hover {
color: #c9d1d9;
background: rgba(255,255,255,0.04);
}
.nav-item--active {
color: var(--accent);
background: rgba(0,212,255,0.06);
border-left-color: var(--accent);
}
.nav-icon { display: flex; align-items: center; flex-shrink: 0; }
.nav-divider { height: 1px; background: var(--border); margin: 8px 0; }
/* Sidebar footer */
.sidebar-footer {
padding: 12px 16px;
border-top: 1px solid var(--border);
}
.cli-badge {
font-family: 'JetBrains Mono', monospace;
font-size: 10px;
padding: 3px 8px;
border-radius: 4px;
display: inline-flex;
align-items: center;
gap: 5px;
margin-bottom: 6px;
}
.cli-badge--ok { color: var(--safe); background: rgba(0,230,118,0.08); }
.cli-badge--warn { color: var(--warn); background: rgba(255,179,0,0.08); }
.version-label {
font-family: 'JetBrains Mono', monospace;
font-size: 10px;
color: var(--muted);
}
/* Mobile sidebar */
.sidebar-overlay {
display: none;
position: fixed;
inset: 0;
background: rgba(0,0,0,0.6);
z-index: 99;
}
@media (max-width: 768px) {
.sidebar {
position: fixed;
top: 0; left: 0; bottom: 0;
transform: translateX(-100%);
}
.sidebar.open { transform: translateX(0); }
.sidebar-overlay.open { display: block; }
}
/* ---------------------------------------------------------------
Status pill
--------------------------------------------------------------- */
.status-pill {
display: flex;
align-items: center;
gap: 6px;
padding: 4px 10px;
border-radius: 20px;
font-size: 11px;
font-family: 'JetBrains Mono', monospace;
}
.status-pill--loading { background: rgba(74,85,104,0.3); color: var(--muted); }
.status-pill--healthy { background: rgba(0,230,118,0.1); color: var(--safe); border: 1px solid rgba(0,230,118,0.2); }
.status-pill--unhealthy { background: rgba(255,59,59,0.1); color: var(--threat); border: 1px solid rgba(255,59,59,0.2); }
.status-dot {
width: 6px; height: 6px;
border-radius: 50%;
background: currentColor;
animation: pulse-dot 2s ease-in-out infinite;
}
@keyframes pulse-dot {
0%, 100% { opacity: 1; }
50% { opacity: 0.4; }
}
/* ---------------------------------------------------------------
Top bar
--------------------------------------------------------------- */
.topbar {
height: 52px;
background: var(--s-900);
border-bottom: 1px solid var(--border);
display: flex;
align-items: center;
gap: 12px;
padding: 0 20px;
flex-shrink: 0;
}
.topbar-menu-btn {
background: none;
border: none;
color: var(--muted);
cursor: pointer;
padding: 4px;
border-radius: 4px;
display: none;
}
.topbar-menu-btn:hover { color: #c9d1d9; }
@media (max-width: 768px) { .topbar-menu-btn { display: flex; } }
.topbar-breadcrumb { flex: 1; }
.topbar-page { font-weight: 600; font-size: 14px; color: #e6edf3; }
/* ---------------------------------------------------------------
Flash messages
--------------------------------------------------------------- */
.flash {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 20px;
font-size: 13px;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.flash--success { background: rgba(0,230,118,0.08); color: var(--safe); border-left: 3px solid var(--safe); }
.flash--error { background: rgba(255,59,59,0.08); color: var(--threat); border-left: 3px solid var(--threat); }
.flash--warning { background: rgba(255,179,0,0.08); color: var(--warn); border-left: 3px solid var(--warn); }
.flash--info { background: rgba(0,212,255,0.08); color: var(--accent); border-left: 3px solid var(--accent); }
.flash-icon { font-size: 14px; flex-shrink: 0; }
.flash-text { flex: 1; }
.flash-close {
background: none; border: none; cursor: pointer;
color: currentColor; opacity: 0.6; font-size: 12px; padding: 2px 6px;
}
.flash-close:hover { opacity: 1; }
/* ---------------------------------------------------------------
Page headings
--------------------------------------------------------------- */
.page-title {
font-size: 22px;
font-weight: 600;
color: #e6edf3;
line-height: 1.2;
}
.page-sub { font-size: 13px; color: var(--muted); margin-top: 2px; }
/* ---------------------------------------------------------------
Stat cards
--------------------------------------------------------------- */
.stat-card {
background: var(--s-800);
border: 1px solid var(--border);
border-radius: 10px;
padding: 18px 20px;
border-top: 2px solid transparent;
transition: border-color 0.2s;
}
.stat-card--threat { border-top-color: var(--threat); }
.stat-card--warn { border-top-color: var(--warn); }
.stat-card--accent { border-top-color: var(--accent); }
.stat-card--safe { border-top-color: var(--safe); }
.stat-label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--muted); margin-bottom: 6px; }
.stat-value { font-family: 'JetBrains Mono', monospace; font-size: 32px; font-weight: 600; line-height: 1; color: #e6edf3; margin-bottom: 4px; }
.stat-sub { font-size: 11px; color: var(--muted); }
/* ---------------------------------------------------------------
Panels
--------------------------------------------------------------- */
.panel {
background: var(--s-800);
border: 1px solid var(--border);
border-radius: 10px;
overflow: hidden;
}
.panel-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 14px 18px;
border-bottom: 1px solid var(--border);
}
.panel-title { font-size: 13px; font-weight: 600; color: #e6edf3; }
.panel-link { font-size: 12px; color: var(--accent); text-decoration: none; }
.panel-link:hover { text-decoration: underline; }
.panel-body { padding: 16px 18px; }
/* ---------------------------------------------------------------
Data tables
--------------------------------------------------------------- */
.data-table { width: 100%; border-collapse: collapse; }
.data-table th {
text-align: left;
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--muted);
font-weight: 600;
padding: 10px 14px;
border-bottom: 1px solid var(--border);
background: var(--s-700);
white-space: nowrap;
}
.data-table td {
padding: 10px 14px;
border-bottom: 1px solid rgba(255,255,255,0.03);
vertical-align: middle;
color: #c9d1d9;
}
.data-table tr:last-child td { border-bottom: none; }
.data-table tbody tr:hover { background: rgba(255,255,255,0.02); }
/* ---------------------------------------------------------------
Badges
--------------------------------------------------------------- */
.badge {
display: inline-flex;
align-items: center;
padding: 2px 7px;
border-radius: 4px;
font-family: 'JetBrains Mono', monospace;
font-size: 10px;
font-weight: 500;
letter-spacing: 0.04em;
text-transform: lowercase;
}
.badge-red { background: rgba(255,59,59,0.15); color: #ff7b7b; border: 1px solid rgba(255,59,59,0.25); }
.badge-amber { background: rgba(255,179,0,0.12); color: #ffc233; border: 1px solid rgba(255,179,0,0.2); }
.badge-green { background: rgba(0,230,118,0.1); color: #33e68e; border: 1px solid rgba(0,230,118,0.2); }
.badge-cyan { background: rgba(0,212,255,0.1); color: #33deff; border: 1px solid rgba(0,212,255,0.2); }
.badge-blue { background: rgba(58,130,246,0.15); color: #60a5fa; border: 1px solid rgba(58,130,246,0.2); }
.badge-purple { background: rgba(139,92,246,0.12); color: #a78bfa; border: 1px solid rgba(139,92,246,0.2); }
.badge-gray { background: rgba(74,85,104,0.3); color: #8b949e; border: 1px solid rgba(74,85,104,0.3); }
/* ---------------------------------------------------------------
Buttons
--------------------------------------------------------------- */
.btn-primary {
display: inline-flex; align-items: center; gap: 6px;
padding: 7px 16px;
background: var(--accent);
color: #000;
font-size: 12px;
font-weight: 600;
border: none;
border-radius: 6px;
cursor: pointer;
text-decoration: none;
transition: background 0.15s, transform 0.1s;
white-space: nowrap;
}
.btn-primary:hover { background: var(--accent-dim); }
.btn-primary:active { transform: scale(0.97); }
.btn-secondary {
display: inline-flex; align-items: center; gap: 6px;
padding: 7px 14px;
background: var(--s-600);
color: #c9d1d9;
font-size: 12px;
font-weight: 500;
border: 1px solid var(--border);
border-radius: 6px;
cursor: pointer;
text-decoration: none;
transition: background 0.15s;
white-space: nowrap;
}
.btn-secondary:hover { background: var(--s-500); }
.btn-ghost {
display: inline-flex; align-items: center; gap: 6px;
padding: 7px 14px;
background: transparent;
color: var(--muted);
font-size: 12px;
font-weight: 500;
border: 1px solid var(--border);
border-radius: 6px;
cursor: pointer;
text-decoration: none;
transition: color 0.15s, border-color 0.15s;
white-space: nowrap;
}
.btn-ghost:hover { color: #c9d1d9; border-color: rgba(255,255,255,0.15); }
.btn-danger-sm {
padding: 3px 10px;
font-size: 11px;
font-weight: 500;
background: rgba(255,59,59,0.08);
color: var(--threat);
border: 1px solid rgba(255,59,59,0.2);
border-radius: 4px;
cursor: pointer;
transition: background 0.15s;
white-space: nowrap;
}
.btn-danger-sm:hover { background: rgba(255,59,59,0.18); }
.btn-safe-sm {
padding: 3px 10px;
font-size: 11px;
font-weight: 500;
background: rgba(0,230,118,0.08);
color: var(--safe);
border: 1px solid rgba(0,230,118,0.2);
border-radius: 4px;
cursor: pointer;
transition: background 0.15s;
white-space: nowrap;
}
.btn-safe-sm:hover { background: rgba(0,230,118,0.18); }
.btn-ghost-sm {
padding: 4px 10px;
font-size: 12px;
background: transparent;
color: var(--muted);
border: 1px solid var(--border);
border-radius: 4px;
cursor: pointer;
text-decoration: none;
transition: color 0.15s;
}
.btn-ghost-sm:hover { color: #c9d1d9; }
/* ---------------------------------------------------------------
Form elements
--------------------------------------------------------------- */
.filter-bar {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.filter-select, .filter-input {
padding: 6px 10px;
background: var(--s-700);
border: 1px solid var(--border);
border-radius: 6px;
color: #c9d1d9;
font-size: 12px;
font-family: inherit;
outline: none;
transition: border-color 0.15s;
}
.filter-select:focus, .filter-input:focus {
border-color: rgba(0,212,255,0.4);
}
.filter-input { min-width: 180px; }
.filter-input::placeholder { color: var(--muted); }
.field-label {
display: block;
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--muted);
margin-bottom: 6px;
font-weight: 600;
}
.field-input {
width: 100%;
padding: 8px 12px;
background: var(--s-950);
border: 1px solid rgba(255,255,255,0.1);
border-radius: 6px;
color: #e6edf3;
font-size: 13px;
font-family: inherit;
outline: none;
transition: border-color 0.15s, box-shadow 0.15s;
}
.field-input:focus {
border-color: rgba(0,212,255,0.5);
box-shadow: 0 0 0 3px rgba(0,212,255,0.07);
}
.field-input::placeholder { color: var(--muted); }
.field-hint { font-size: 11px; color: var(--muted); margin-top: 4px; }
/* ---------------------------------------------------------------
Pagination
--------------------------------------------------------------- */
.pagination {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
padding: 12px;
border-top: 1px solid var(--border);
}
/* ---------------------------------------------------------------
Modal
--------------------------------------------------------------- */
.modal-backdrop {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.7);
display: flex;
align-items: center;
justify-content: center;
z-index: 200;
padding: 16px;
backdrop-filter: blur(4px);
}
.modal-backdrop.hidden { display: none; }
.modal {
background: var(--s-800);
border: 1px solid rgba(255,255,255,0.1);
border-radius: 12px;
width: 100%;
max-width: 480px;
overflow: hidden;
animation: modal-in 0.2s ease;
}
@keyframes modal-in {
from { opacity: 0; transform: translateY(-12px) scale(0.97); }
to { opacity: 1; transform: none; }
}
.modal-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px 20px;
border-bottom: 1px solid var(--border);
}
.modal-title { font-size: 15px; font-weight: 600; color: #e6edf3; }
.modal-close {
background: none; border: none; cursor: pointer;
color: var(--muted); font-size: 14px; padding: 4px 8px;
}
.modal-close:hover { color: #c9d1d9; }
.modal-body { padding: 20px; }
.modal-footer { display: flex; justify-content: flex-end; gap: 8px; margin-top: 8px; }
/* ---------------------------------------------------------------
Empty states
--------------------------------------------------------------- */
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 48px 24px;
text-align: center;
}
.empty-icon { font-size: 32px; margin-bottom: 12px; opacity: 0.4; }
.empty-text { font-size: 14px; font-weight: 600; color: #6e7681; margin-bottom: 4px; }
.empty-sub { font-size: 12px; color: var(--muted); }
/* ---------------------------------------------------------------
CLI unavailable banner
--------------------------------------------------------------- */
.cli-unavail-banner {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 14px 18px;
background: rgba(255,179,0,0.05);
border: 1px solid rgba(255,179,0,0.2);
border-radius: 8px;
font-size: 13px;
color: #c9d1d9;
}
/* ---------------------------------------------------------------
API Key reveal
--------------------------------------------------------------- */
.apikey-reveal {
padding: 16px 18px;
background: rgba(0,230,118,0.05);
border: 1px solid rgba(0,230,118,0.2);
border-radius: 8px;
}
.apikey-header { font-size: 13px; margin-bottom: 10px; display: flex; flex-wrap: wrap; gap: 8px; }
.apikey-box {
position: relative;
padding: 12px 16px;
background: var(--s-950);
border: 1px solid rgba(0,230,118,0.2);
border-radius: 6px;
cursor: pointer;
word-break: break-all;
}
.apikey-box:hover { border-color: rgba(0,230,118,0.4); }
.apikey-copy-hint {
display: block;
margin-top: 6px;
font-size: 10px;
color: var(--muted);
font-family: 'JetBrains Mono', monospace;
}
/* ---------------------------------------------------------------
Tabs
--------------------------------------------------------------- */
.tab-bar {
display: flex;
gap: 0;
border-bottom: 1px solid var(--border);
overflow-x: auto;
}
.tab-item {
padding: 10px 18px;
font-size: 13px;
font-weight: 500;
color: var(--muted);
text-decoration: none;
border-bottom: 2px solid transparent;
transition: color 0.15s;
white-space: nowrap;
display: flex;
align-items: center;
gap: 6px;
margin-bottom: -1px;
}
.tab-item:hover { color: #c9d1d9; }
.tab-item--active { color: var(--accent); border-bottom-color: var(--accent); }
.tab-count {
font-family: 'JetBrains Mono', monospace;
font-size: 10px;
padding: 1px 5px;
background: rgba(255,255,255,0.08);
border-radius: 3px;
}
/* ---------------------------------------------------------------
Utility helpers
--------------------------------------------------------------- */
.text-accent { color: var(--accent); }
.text-threat { color: var(--threat); }
.text-safe { color: var(--safe); }
.text-warn { color: var(--warn); }
.text-muted { color: var(--muted); }
/* Smooth page load */
body { opacity: 0; transition: opacity 0.18s ease; }
body.ready { opacity: 1; }