Compare commits
22
Commits
a34ff96490
...
v0.4.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13a78f4268 | ||
|
|
9f07d41cb0 | ||
|
|
8eeb7894a3 | ||
|
|
e86518cab1 | ||
|
|
570ac20a5c | ||
|
|
393ebcdf0c | ||
|
|
f5bcc55a29 | ||
|
|
31bb8b21c2 | ||
|
|
de22f035dc | ||
|
|
6b9bf3cd5f | ||
|
|
9a56fc5b48 | ||
|
|
b9f2b0443c | ||
|
|
49a8fa1154 | ||
|
|
b8328f6998 | ||
|
|
2a639a6b59 | ||
|
|
552abffd29 | ||
|
|
31cef44bf3 | ||
|
|
6e2ff3f7ee | ||
|
|
4168e9990b | ||
|
|
0984af25bc | ||
|
|
7c3657d015 | ||
|
|
c22d452720 |
No files matched your search
@@ -7,3 +7,5 @@
|
|||||||
.idea/
|
.idea/
|
||||||
test/
|
test/
|
||||||
.gitea/
|
.gitea/
|
||||||
|
unraid/
|
||||||
|
deploy/
|
||||||
+16
-10
@@ -1,6 +1,7 @@
|
|||||||
# Builds the image on every push to main, pushes it to the Gitea registry (tagged
|
# Builds the image on every push to main, pushes it to the Gitea registry (tagged
|
||||||
# :latest AND the short commit SHA, for rollback) and deploys the stack on Unraid
|
# :main AND the short commit SHA, for rollback) and deploys the stack on Unraid
|
||||||
# from deploy/unraid/compose.yaml (Tom's personal Unraid setup).
|
# from deploy/unraid/compose.yaml (Tom's personal Unraid setup). Releases (:latest,
|
||||||
|
# :X.Y.Z) come from version tags in release.yml and are never deployed here.
|
||||||
#
|
#
|
||||||
# The deploy works because the act_runner runs ON Unraid and hands its Docker
|
# The deploy works because the act_runner runs ON Unraid and hands its Docker
|
||||||
# socket to the job: every `docker` command here talks to the Unraid daemon, so
|
# socket to the job: every `docker` command here talks to the Unraid daemon, so
|
||||||
@@ -58,13 +59,18 @@ jobs:
|
|||||||
id: sha
|
id: sha
|
||||||
run: echo "short=$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT"
|
run: echo "short=$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
- name: Build and push (:latest and :<sha>)
|
# amd64 only: these builds exist for the Unraid deploy (x86_64), and a
|
||||||
|
# single platform keeps every push fast. Releases are multi-arch.
|
||||||
|
- name: Build and push (:main and :<sha>)
|
||||||
uses: docker/build-push-action@v6
|
uses: docker/build-push-action@v6
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
|
platforms: linux/amd64
|
||||||
push: true
|
push: true
|
||||||
|
build-args: |
|
||||||
|
VERSION=0.0.0-dev+${{ steps.sha.outputs.short }}
|
||||||
tags: |
|
tags: |
|
||||||
${{ env.IMAGE }}:latest
|
${{ env.IMAGE }}:main
|
||||||
${{ env.IMAGE }}:${{ steps.sha.outputs.short }}
|
${{ env.IMAGE }}:${{ steps.sha.outputs.short }}
|
||||||
|
|
||||||
deploy:
|
deploy:
|
||||||
@@ -111,15 +117,15 @@ jobs:
|
|||||||
docker compose -f deploy/unraid/compose.yaml up -d --wait --remove-orphans
|
docker compose -f deploy/unraid/compose.yaml up -d --wait --remove-orphans
|
||||||
|
|
||||||
# /health answers 200 only when the app runs AND reads its database. It is
|
# /health answers 200 only when the app runs AND reads its database. It is
|
||||||
# checked from inside proxynet, the same way NPM reaches the app. The probe
|
# checked from inside proxynet on both ports: 8080 is the trap, reached the
|
||||||
# comes from a private address, so /health is exempt from the trap even
|
# same way NPM reaches it (the probe comes from a private address, so /health
|
||||||
# though the Host header (flypaper) is unknown. A failure marks the run red;
|
# is exempt from the trap), 8081 is the dashboard. A failure marks the run
|
||||||
# the rollback stays a deliberate step.
|
# red; the rollback stays a deliberate step.
|
||||||
- name: Health gate
|
- name: Health gate
|
||||||
run: |
|
run: |
|
||||||
for attempt in $(seq 1 30); do
|
for attempt in $(seq 1 30); do
|
||||||
if docker run --rm --network proxynet busybox:1.37 \
|
if docker run --rm --network proxynet busybox:1.37 sh -c \
|
||||||
wget -qO- http://flypaper:8080/health; then
|
'wget -qO- http://flypaper:8080/health && wget -qO- http://flypaper:8081/health'; then
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
sleep 2
|
sleep 2
|
||||||
|
|||||||
@@ -0,0 +1,115 @@
|
|||||||
|
# Builds a release when a version tag (vX.Y.Z) is pushed: a multi-arch image
|
||||||
|
# (linux/amd64, linux/arm64) is tagged :X.Y.Z, :X.Y, :X and :latest in the Gitea
|
||||||
|
# registry, and a Gitea release is created with the matching section of
|
||||||
|
# CHANGELOG.md as notes. Nothing is deployed; Tom's Unraid follows :main through
|
||||||
|
# deploy.yml.
|
||||||
|
#
|
||||||
|
# A pre-release tag such as v0.2.0-rc.1 only gets its own :0.2.0-rc.1 tag and a
|
||||||
|
# release marked as pre-release; :latest and the short tags stay on the last
|
||||||
|
# stable version.
|
||||||
|
#
|
||||||
|
# Required repository secrets: REGISTRY_USER, REGISTRY_TOKEN (see deploy.yml).
|
||||||
|
# The release itself uses the job's built-in token.
|
||||||
|
|
||||||
|
name: Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: ["v*"]
|
||||||
|
|
||||||
|
env:
|
||||||
|
IMAGE: gitea.anticarnist.de/tom/flypaper
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
image:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
outputs:
|
||||||
|
version: ${{ steps.version.outputs.version }}
|
||||||
|
prerelease: ${{ steps.version.outputs.prerelease }}
|
||||||
|
steps:
|
||||||
|
- name: Check out the source
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Read the version from the tag
|
||||||
|
id: version
|
||||||
|
run: |
|
||||||
|
version="${GITHUB_REF_NAME#v}"
|
||||||
|
if ! echo "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then
|
||||||
|
echo "Tag $GITHUB_REF_NAME is not vX.Y.Z" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||||
|
{
|
||||||
|
echo "tags<<EOF"
|
||||||
|
echo "$IMAGE:$version"
|
||||||
|
case "$version" in
|
||||||
|
*-*) ;;
|
||||||
|
*)
|
||||||
|
echo "$IMAGE:${version%.*}"
|
||||||
|
echo "$IMAGE:${version%%.*}"
|
||||||
|
echo "$IMAGE:latest"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
echo "EOF"
|
||||||
|
} >> "$GITHUB_OUTPUT"
|
||||||
|
case "$version" in
|
||||||
|
*-*) echo "prerelease=true" >> "$GITHUB_OUTPUT" ;;
|
||||||
|
*) echo "prerelease=false" >> "$GITHUB_OUTPUT" ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: Log in to the Gitea registry
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: gitea.anticarnist.de
|
||||||
|
username: ${{ secrets.REGISTRY_USER }}
|
||||||
|
password: ${{ secrets.REGISTRY_TOKEN }}
|
||||||
|
|
||||||
|
# No QEMU: the Dockerfile compiles natively on the runner and cross-publishes
|
||||||
|
# for each architecture; the arm64 runtime stage only copies files. Setting
|
||||||
|
# up QEMU would also register binfmt handlers on the Unraid host kernel.
|
||||||
|
- name: Build and push the release tags
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
push: true
|
||||||
|
build-args: |
|
||||||
|
VERSION=${{ steps.version.outputs.version }}
|
||||||
|
tags: ${{ steps.version.outputs.tags }}
|
||||||
|
|
||||||
|
release:
|
||||||
|
needs: image
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Check out the source
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# The notes are the CHANGELOG.md section of this version, from its heading
|
||||||
|
# up to the next one. If the API call fails, the images are still pushed;
|
||||||
|
# the release can then be created by hand (deploy/unraid/README.md).
|
||||||
|
- name: Create the Gitea release
|
||||||
|
env:
|
||||||
|
VERSION: ${{ needs.image.outputs.version }}
|
||||||
|
PRERELEASE: ${{ needs.image.outputs.prerelease }}
|
||||||
|
TOKEN: ${{ github.token }}
|
||||||
|
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases
|
||||||
|
run: |
|
||||||
|
notes=$(awk -v version="$VERSION" '
|
||||||
|
/^## \[/ { if (found) exit; if (index($0, "[" version "]")) { found = 1; next } }
|
||||||
|
/^\[[^]]+\]: / { if (found) exit }
|
||||||
|
found { print }
|
||||||
|
' CHANGELOG.md)
|
||||||
|
[ -n "$notes" ] || notes="See CHANGELOG.md."
|
||||||
|
jq -n \
|
||||||
|
--arg tag "$GITHUB_REF_NAME" \
|
||||||
|
--arg name "Flypaper $VERSION" \
|
||||||
|
--arg body "$notes" \
|
||||||
|
--argjson prerelease "$PRERELEASE" \
|
||||||
|
'{tag_name: $tag, name: $name, body: $body, prerelease: $prerelease}' > release.json
|
||||||
|
curl -fsS -X POST "$API" \
|
||||||
|
-H "Authorization: token $TOKEN" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
--data @release.json
|
||||||
+131
@@ -0,0 +1,131 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to Flypaper are documented in this file. The format follows
|
||||||
|
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
|
||||||
|
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.4.0] - 2026-11-15
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- MCP results now include fields whose value is `null` (e.g. `since` of `get_stats` with
|
||||||
|
`period=all`, a missing label in `top`) instead of leaving them out, so they match the
|
||||||
|
tools' output schemas.
|
||||||
|
- MCP tools answer unknown or missing parameters with a readable error instead of
|
||||||
|
"An error occurred invoking …" or silently ignoring them, e.g. `unknown parameter 'by';
|
||||||
|
expected 'dimension' (ips|countries|providers|targets|user_agents)`. `top` lists the allowed
|
||||||
|
values of `dimension` in its input schema. Invalid arguments are logged as warnings.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Rejected connections stand out on the dashboard: the "Abgelehnt" metric shows the last
|
||||||
|
24 hours, and the catch list marks them with an "Abgelehnt" badge. Outcomes are shown in
|
||||||
|
German. Top lists and hold times still count only real catches.
|
||||||
|
- The "Haltezeit gesamt" metric shows the average hold time per catch below it.
|
||||||
|
- The catch list on the dashboard has filters for period, outcome, country and a free-text
|
||||||
|
search over IP, provider, target and user agent. A click on a top 10 row filters the list by
|
||||||
|
that country, provider, IP or target (a second click removes it). Active filters show as
|
||||||
|
chips with the number of matches, live in the URL (`?land=HK&ausgang=abgelehnt&q=…`) and
|
||||||
|
survive the auto-refresh; "Weitere laden" shows up to 500 entries. Metrics and top 10 stay
|
||||||
|
unfiltered.
|
||||||
|
- The outcome "Abgebrochen" is now called "Aufgegeben".
|
||||||
|
- Dashboard polish: equal metric tiles with a one-line note each (unique IPs show the last
|
||||||
|
24 hours), map and top 10 card of equal height with a larger legend and visible
|
||||||
|
small-country markers, country and provider names in the regular font with a separate share
|
||||||
|
column, and German number formats throughout (e.g. `1.675` bytes, `15.11. 20:01:50`).
|
||||||
|
|
||||||
|
## [0.3.1] - 2026-11-15
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- The dashboard's top 10 lists share one card with tabs (Länder, Provider, IPs, Ziele); the
|
||||||
|
selected tab survives the auto-refresh.
|
||||||
|
|
||||||
|
## [0.3.0] - 2026-11-15
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Settings section "Haltemethode": content (HTML filler text, random plain text or alternating
|
||||||
|
per catch), pause and chunk size ranges and the maximum hold time, with an estimate of the
|
||||||
|
bandwidth per trapped connection and its own reset button. Changes apply to the next catch
|
||||||
|
without a restart.
|
||||||
|
- Plain-text drip strategy (`text-drip`), served as `text/plain`.
|
||||||
|
- Each catch stores its strategy with the parameters in use, e.g. `text-drip 50-1000ms 1-64B`;
|
||||||
|
MCP results include it as `strategy`.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- The maximum hold time moved from the general settings to "Haltemethode".
|
||||||
|
- Saving one settings section no longer resets the values saved in another.
|
||||||
|
- Redesigned settings page with sections, side navigation and choice cards.
|
||||||
|
- Redesigned dashboard with weighted metrics, a more compact world map, share bars in the top
|
||||||
|
tables and a short guide while no catches exist yet.
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
|
||||||
|
- Trap paths and known hosts, with their settings, the `Flypaper__Http__KnownHosts` and
|
||||||
|
`Flypaper__Http__TrapPaths` variables and the matching logic: every request on the trap port
|
||||||
|
is caught, only `/health` from private addresses is answered. Saved overrides are deleted on
|
||||||
|
start; the old variables are ignored with a warning in the log.
|
||||||
|
|
||||||
|
## [0.2.0] - 2026-11-15
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- MCP server at `/mcp` on the dashboard port (Streamable HTTP) with read-only tools
|
||||||
|
`get_stats`, `list_catches`, `top`, `longest_catches` and `lookup_ip`, returning structured
|
||||||
|
JSON.
|
||||||
|
- Bearer tokens for MCP, created, listed and revoked on the settings page and stored only as
|
||||||
|
SHA-256 hashes; optional fixed token via `Flypaper__Mcp__Token`.
|
||||||
|
|
||||||
|
## [0.1.1] - 2026-11-15
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Small countries without an outline on the world map (e.g. Hong Kong, Singapore, Macau,
|
||||||
|
Bahrain, Malta) are now shown as markers with the same colour scale and tooltip.
|
||||||
|
- The latest catches table no longer overflows its card; numbers always stay visible.
|
||||||
|
- Requests without a `Host` header show "(ohne Host)" instead of `_`.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Common short country names on the map and in the tables, e.g. "Taiwan" instead of
|
||||||
|
"Republik China", "Hongkong", "USA".
|
||||||
|
- Larger hover area for map markers.
|
||||||
|
- Shorter README; reverse proxy, Unraid, configuration and release details moved to `docs/`.
|
||||||
|
|
||||||
|
## [0.1.0] - 2026-11-14
|
||||||
|
|
||||||
|
First release.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- HTTP tarpit on its own port (8080): every request is caught and answered with endless,
|
||||||
|
plausible HTML in random chunks of 1–64 bytes with random pauses of 50 ms–1 s.
|
||||||
|
- Connection governor with limits overall and per IP and a maximum hold time; requests
|
||||||
|
without a free slot get a quick 404.
|
||||||
|
- Optional known hosts that are caught only on configurable trap paths.
|
||||||
|
- Client IP from `X-Real-IP` / `X-Forwarded-For`, trusting private networks by default.
|
||||||
|
- One log line per catch and storage in SQLite, enriched with country, city and ASN from the
|
||||||
|
DB-IP Lite databases (downloaded and refreshed monthly, existing catches backfilled).
|
||||||
|
- Dashboard on its own port (8081): totals, world map, top countries, providers, IPs and
|
||||||
|
paths, latest catches with expandable rows.
|
||||||
|
- Settings page for trap paths, known hosts, limits, retention and the private-network filter,
|
||||||
|
effective without a restart; deleting private or all catches.
|
||||||
|
- Admin password set on first visit (stored as a salted hash) and changeable later, or fixed
|
||||||
|
with `Flypaper__Admin__Password`.
|
||||||
|
- Daily retention cleanup (90 days by default), `/health` endpoint, Docker image running as
|
||||||
|
non-root with all data under `/data`.
|
||||||
|
- Public images for `linux/amd64` and `linux/arm64` in the Gitea registry.
|
||||||
|
- Unraid Docker template; when started as root, the container hands `/data` to its app user
|
||||||
|
and drops privileges.
|
||||||
|
|
||||||
|
[Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.4.0...main
|
||||||
|
[0.4.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.4.0
|
||||||
|
[0.3.1]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.3.1
|
||||||
|
[0.3.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.3.0
|
||||||
|
[0.2.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.2.0
|
||||||
|
[0.1.1]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.1.1
|
||||||
|
[0.1.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.1.0
|
||||||
@@ -4,5 +4,6 @@
|
|||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||||
|
<Version>0.0.0-dev</Version>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -11,6 +11,7 @@
|
|||||||
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.15" />
|
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.15" />
|
||||||
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.15" />
|
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.15" />
|
||||||
<PackageVersion Include="MaxMind.GeoIP2" Version="6.1.0" />
|
<PackageVersion Include="MaxMind.GeoIP2" Version="6.1.0" />
|
||||||
|
<PackageVersion Include="ModelContextProtocol.AspNetCore" Version="2.4.0" />
|
||||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.15" />
|
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.15" />
|
||||||
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" />
|
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
+20
-7
@@ -1,4 +1,8 @@
|
|||||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
# The SDK stage runs natively on the build machine and cross-publishes for the
|
||||||
|
# target architecture. The runtime stage only copies files and sets metadata, so a
|
||||||
|
# multi-arch build needs no QEMU emulation at all.
|
||||||
|
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||||
|
ARG TARGETARCH
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
|
|
||||||
COPY Directory.Build.props Directory.Packages.props ./
|
COPY Directory.Build.props Directory.Packages.props ./
|
||||||
@@ -7,25 +11,34 @@ COPY src/Flypaper.GeoIp/Flypaper.GeoIp.csproj src/Flypaper.GeoIp/
|
|||||||
COPY src/Flypaper.Http/Flypaper.Http.csproj src/Flypaper.Http/
|
COPY src/Flypaper.Http/Flypaper.Http.csproj src/Flypaper.Http/
|
||||||
COPY src/Flypaper.Storage/Flypaper.Storage.csproj src/Flypaper.Storage/
|
COPY src/Flypaper.Storage/Flypaper.Storage.csproj src/Flypaper.Storage/
|
||||||
COPY src/Flypaper.Web/Flypaper.Web.csproj src/Flypaper.Web/
|
COPY src/Flypaper.Web/Flypaper.Web.csproj src/Flypaper.Web/
|
||||||
RUN dotnet restore src/Flypaper.Web/Flypaper.Web.csproj
|
RUN dotnet restore src/Flypaper.Web/Flypaper.Web.csproj -a $TARGETARCH
|
||||||
|
|
||||||
COPY src/ src/
|
COPY src/ src/
|
||||||
RUN dotnet publish src/Flypaper.Web/Flypaper.Web.csproj -c Release -o /app --no-restore
|
ARG VERSION=0.0.0-dev
|
||||||
|
RUN dotnet publish src/Flypaper.Web/Flypaper.Web.csproj -c Release -a $TARGETARCH -o /app --no-restore -p:Version=$VERSION \
|
||||||
|
&& mkdir /data
|
||||||
|
|
||||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0
|
FROM mcr.microsoft.com/dotnet/aspnet:10.0
|
||||||
|
ARG VERSION=0.0.0-dev
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
RUN mkdir /data && chown $APP_UID /data
|
LABEL org.opencontainers.image.title="Flypaper" \
|
||||||
|
org.opencontainers.image.description="Self-hosted tarpit that traps and slows down scanning bots, with event logging and analysis." \
|
||||||
|
org.opencontainers.image.source="https://gitea.anticarnist.de/Tom/Flypaper" \
|
||||||
|
org.opencontainers.image.licenses="MIT" \
|
||||||
|
org.opencontainers.image.version=$VERSION
|
||||||
|
|
||||||
ENV ASPNETCORE_HTTP_PORTS=8080 \
|
ENV ASPNETCORE_HTTP_PORTS= \
|
||||||
ConnectionStrings__Flypaper="Data Source=/data/flypaper.db" \
|
ConnectionStrings__Flypaper="Data Source=/data/flypaper.db" \
|
||||||
Flypaper__DataProtection__KeysPath=/data/keys \
|
Flypaper__DataProtection__KeysPath=/data/keys \
|
||||||
Flypaper__GeoIp__Directory=/data/geoip
|
Flypaper__GeoIp__Directory=/data/geoip
|
||||||
|
|
||||||
|
COPY --from=build --chown=1654:1654 /data /data
|
||||||
COPY --from=build /app .
|
COPY --from=build /app .
|
||||||
|
COPY --chmod=755 docker-entrypoint.sh /usr/local/bin/flypaper-entrypoint
|
||||||
|
|
||||||
USER $APP_UID
|
USER $APP_UID
|
||||||
EXPOSE 8080
|
EXPOSE 8080 8081
|
||||||
VOLUME /data
|
VOLUME /data
|
||||||
|
|
||||||
ENTRYPOINT ["dotnet", "Flypaper.Web.dll"]
|
ENTRYPOINT ["flypaper-entrypoint"]
|
||||||
@@ -1,13 +1,9 @@
|
|||||||
# Flypaper
|
# Flypaper
|
||||||
|
|
||||||
Self-hosted tarpit that traps and slows down scanning bots, with event logging and analysis.
|
An HTTP tarpit for scanning bots. Instead of blocking the bots that probe your server for
|
||||||
|
`/.env`, `/.git/config` or `/wp-login.php`, Flypaper lets them in and answers with an endless
|
||||||
Every server on the internet gets a steady stream of bots probing for `/.env`, `/.git/config`,
|
HTML page, a few bytes at a time. While a scanner waits, it isn't scanning someone else, and
|
||||||
`/wp-login.php` and friends, usually sent to the bare IP address or to host names that don't
|
the dashboard shows you who knocked: country, network provider and what they were after.
|
||||||
exist. Blocklists play whack-a-mole with addresses that change daily. Flypaper takes the
|
|
||||||
opposite approach: it lets the bot in and then answers very, very slowly. While a scanner waits
|
|
||||||
for an endless HTML page that trickles in a few bytes at a time, it isn't scanning someone
|
|
||||||
else, and every catch is logged with its origin for you to look at.
|
|
||||||
|
|
||||||
## How it works
|
## How it works
|
||||||
|
|
||||||
@@ -15,69 +11,42 @@ else, and every catch is logged with its origin for you to look at.
|
|||||||
flowchart LR
|
flowchart LR
|
||||||
bot["Scanner bot"] -->|"GET /.env<br/>Host: 203.0.113.7"| proxy["Reverse proxy"]
|
bot["Scanner bot"] -->|"GET /.env<br/>Host: 203.0.113.7"| proxy["Reverse proxy"]
|
||||||
proxy -->|"known site"| apps["Your apps"]
|
proxy -->|"known site"| apps["Your apps"]
|
||||||
proxy -->|"unknown host or trap path<br/>+ X-Real-IP"| flypaper["Flypaper"]
|
proxy -->|"unknown host<br/>+ X-Real-IP"| flypaper["Flypaper"]
|
||||||
flypaper -.->|"endless HTML,<br/>a few bytes at a time"| bot
|
flypaper -.->|"endless HTML,<br/>a few bytes at a time"| bot
|
||||||
flypaper --> db[("SQLite:<br/>catches, settings")]
|
flypaper --> db[("SQLite:<br/>catches, settings")]
|
||||||
you["You (LAN)"] -->|"dashboard host"| flypaper
|
you["You (LAN)"] -->|"dashboard, port 8081"| flypaper
|
||||||
```
|
```
|
||||||
|
|
||||||
1. Your reverse proxy keeps serving your real sites. Everything it has no site for (the
|
- Your reverse proxy sends everything it has no site for (its catch-all server) to Flypaper's
|
||||||
default/catch-all server) goes to Flypaper, optionally also a few bait paths on your real
|
trap port `8080`.
|
||||||
domains.
|
- Every request there gets `200 OK` and an endless page in random chunks with random pauses,
|
||||||
2. Flypaper looks at the `Host` header. A request for a host it doesn't know, or for a trap path,
|
within limits per IP, overall and per catch.
|
||||||
is caught. Requests for a known host (the dashboard's) pass through to the dashboard.
|
- Each catch is logged and stored with its origin (DB-IP GeoIP); the dashboard on port `8081`
|
||||||
3. A caught request gets `200 OK` and an endless, plausible-looking HTML page: random chunks
|
shows maps and tables.
|
||||||
of 1 to 64 bytes with random pauses of 50 ms to 1 s in between.
|
- AI assistants such as Claude can query the catches over MCP: [docs/mcp.md](docs/mcp.md).
|
||||||
4. A connection governor caps the number of catches overall and per IP and ends every catch
|
|
||||||
after a maximum hold time. If there is no free slot, the request gets a quick `404`.
|
|
||||||
5. When a catch ends, Flypaper logs one line and stores the event in SQLite, enriched with
|
|
||||||
country, city and network provider (ASN) from the free DB-IP databases.
|
|
||||||
|
|
||||||
## Features
|
More: [how it works and all features](docs/overview.md).
|
||||||
|
|
||||||
- **Traps** for unknown hosts (catch-all) and for configurable trap paths such as `/.env`,
|
|
||||||
`/.git/*` or `/wp-login.php`
|
|
||||||
- **Slow delivery** of endless generated HTML with irregular timing
|
|
||||||
- **Limits**: maximum connections overall and per IP, maximum hold time per catch
|
|
||||||
- **Dashboard**: totals, a world map, top countries, providers, IPs and paths, the latest
|
|
||||||
catches with expandable details; login with an admin password
|
|
||||||
- **GeoIP**: country, city and ASN per catch from DB-IP Lite, downloaded and refreshed
|
|
||||||
monthly; existing catches are filled in once the databases are available
|
|
||||||
- **Settings page**: trap paths, extra known hosts, limits and retention, changed at runtime
|
|
||||||
without a restart
|
|
||||||
- **Retention**: old catches are deleted daily (90 days by default); catches from private
|
|
||||||
networks are not stored by default; buttons to delete private or all catches
|
|
||||||
- **One log line per catch**, so `docker logs` alone shows whether the trap works
|
|
||||||
- **Health endpoint** `/health` for container health checks (answers only to private
|
|
||||||
addresses)
|
|
||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
There is no public image; build it from source.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone <repository-url> flypaper
|
docker run -d --name flypaper --restart unless-stopped \
|
||||||
cd flypaper
|
-p 8080:8080 -p 127.0.0.1:8081:8081 \
|
||||||
|
-v flypaper-data:/data \
|
||||||
|
gitea.anticarnist.de/tom/flypaper:latest
|
||||||
```
|
```
|
||||||
|
|
||||||
Create a `compose.yaml` next to the `Dockerfile`:
|
Or with Compose:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
services:
|
services:
|
||||||
flypaper:
|
flypaper:
|
||||||
build: .
|
image: gitea.anticarnist.de/tom/flypaper:latest
|
||||||
image: flypaper:local
|
|
||||||
container_name: flypaper
|
container_name: flypaper
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
- "8080:8080"
|
- "8080:8080" # trap
|
||||||
environment:
|
- "127.0.0.1:8081:8081" # dashboard
|
||||||
TZ: Europe/Berlin
|
|
||||||
# Host names that reach the dashboard. Every other Host header is trapped.
|
|
||||||
Flypaper__Http__KnownHosts__0: localhost
|
|
||||||
# The reverse proxy that sets X-Real-IP (IP or CIDR), see below.
|
|
||||||
Flypaper__Http__TrustedProxies__0: 172.16.0.0/12
|
|
||||||
Flypaper__Admin__Password: ${FLYPAPER_ADMIN_PASSWORD:?set FLYPAPER_ADMIN_PASSWORD}
|
|
||||||
volumes:
|
volumes:
|
||||||
- flypaper-data:/data
|
- flypaper-data:/data
|
||||||
|
|
||||||
@@ -85,113 +54,21 @@ volumes:
|
|||||||
flypaper-data:
|
flypaper-data:
|
||||||
```
|
```
|
||||||
|
|
||||||
```bash
|
Port `8080` is the trap, port `8081` the dashboard (keep it in your LAN), and `/data` holds the
|
||||||
FLYPAPER_ADMIN_PASSWORD='a-long-random-password' docker compose up -d --build
|
database, login keys and GeoIP files. Images exist for `linux/amd64` and `linux/arm64`. Open
|
||||||
```
|
<http://localhost:8081>: the first visit sets the admin password (changeable later on the
|
||||||
|
settings page). Try the trap with `curl -N http://localhost:8080/`.
|
||||||
|
|
||||||
- Dashboard: <http://localhost:8080>, log in with the password.
|
On Unraid, use the template: [docs/unraid.md](docs/unraid.md).
|
||||||
- See the trap in action (any unknown host works):
|
|
||||||
|
|
||||||
```bash
|
## Connect your reverse proxy
|
||||||
curl -N -H "Host: example.invalid" http://localhost:8080/
|
|
||||||
```
|
|
||||||
|
|
||||||
This catch comes from a private address and is therefore not stored; the log line ends with
|
Make Flypaper the target of your proxy's catch-all (default) server on port `8080`, so every
|
||||||
`(not stored)`.
|
request for a host you don't serve lands in the trap. The proxy must set `X-Real-IP`; Flypaper
|
||||||
|
trusts proxies in private networks by default. Turn off response buffering so the drip reaches
|
||||||
|
the bot.
|
||||||
|
|
||||||
The container runs as a non-root user (UID 1654) and keeps everything under `/data`: the SQLite
|
Plain nginx, with Flypaper on the same host:
|
||||||
database, the Data Protection keys for logins and the GeoIP databases. A named volume gets
|
|
||||||
the right owner automatically; for a bind mount, `chown 1654:1654` the host folder first.
|
|
||||||
|
|
||||||
The files in [`deploy/unraid/`](deploy/unraid) and `.gitea/workflows/deploy.yml` are the
|
|
||||||
author's personal deployment (Gitea Actions to Unraid). They are an example only and not
|
|
||||||
needed to run Flypaper.
|
|
||||||
|
|
||||||
## Behind a reverse proxy
|
|
||||||
|
|
||||||
Flypaper is meant to sit behind the reverse proxy that already owns ports 80/443. Two rules
|
|
||||||
apply to every proxy:
|
|
||||||
|
|
||||||
- **Set `X-Real-IP`** (and `X-Forwarded-For`) to the client address.
|
|
||||||
- **Trust the proxy in Flypaper**: `Flypaper__Http__TrustedProxies__0` must contain the
|
|
||||||
proxy's IP or subnet. Headers from anyone else are ignored, so bots can't fake their
|
|
||||||
address. For a Docker network:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
docker network inspect <network> -f '{{(index .IPAM.Config 0).Subnet}}'
|
|
||||||
```
|
|
||||||
|
|
||||||
Also turn off response buffering for Flypaper, otherwise the proxy collects the drip and the
|
|
||||||
bot never sees it. Flypaper sends `X-Accel-Buffering: no`, which nginx honors.
|
|
||||||
|
|
||||||
### What to send to Flypaper
|
|
||||||
|
|
||||||
- **The catch-all server.** Requests for hosts you don't serve (mostly the bare IP) go to
|
|
||||||
Flypaper. This is where almost all scanners end up.
|
|
||||||
- **Optionally, trap paths on your real domains.** Forward only the bait paths, e.g. `/.env`
|
|
||||||
or `/wp-login.php`, from your real sites to Flypaper. Your domains are unknown to Flypaper,
|
|
||||||
so these requests are caught as well.
|
|
||||||
|
|
||||||
Never forward a whole domain that is listed as a known host: its other paths would show the
|
|
||||||
dashboard login.
|
|
||||||
|
|
||||||
### Nginx Proxy Manager
|
|
||||||
|
|
||||||
Put Flypaper into the same Docker network as NPM (the examples use the container name
|
|
||||||
`flypaper`).
|
|
||||||
|
|
||||||
1. **Settings → Default Site → Congratulations Page.** With this setting NPM writes no
|
|
||||||
default server of its own. Any other choice (404, redirect, HTML) creates one, and nginx
|
|
||||||
refuses to start with two default servers.
|
|
||||||
2. Create `/data/nginx/custom/http.conf` in the NPM container (on the host: inside NPM's
|
|
||||||
data volume):
|
|
||||||
|
|
||||||
```nginx
|
|
||||||
# Catch-all: every HTTP request whose Host matches no proxy host goes to Flypaper.
|
|
||||||
server {
|
|
||||||
listen 80 default_server; # the HTTP port NPM listens on inside its container
|
|
||||||
listen [::]:80 default_server;
|
|
||||||
server_name _;
|
|
||||||
|
|
||||||
location / {
|
|
||||||
# A variable makes nginx resolve the name per request, so NPM still starts
|
|
||||||
# (and serves your sites) while the Flypaper container is down.
|
|
||||||
resolver 127.0.0.11 valid=30s;
|
|
||||||
set $flypaper http://flypaper:8080;
|
|
||||||
proxy_pass $flypaper;
|
|
||||||
|
|
||||||
proxy_set_header Host $host;
|
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
|
||||||
proxy_buffering off;
|
|
||||||
proxy_read_timeout 1h;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
3. Test and reload: `docker exec <npm-container> nginx -t`, then
|
|
||||||
`docker exec <npm-container> nginx -s reload`.
|
|
||||||
4. Optional trap paths on a real domain: in the proxy host's **Advanced** tab add
|
|
||||||
|
|
||||||
```nginx
|
|
||||||
location ~* ^/(\.env|\.git/|wp-login\.php|xmlrpc\.php) {
|
|
||||||
resolver 127.0.0.11 valid=30s;
|
|
||||||
set $flypaper http://flypaper:8080;
|
|
||||||
proxy_pass $flypaper;
|
|
||||||
proxy_set_header Host $host;
|
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
||||||
proxy_buffering off;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
To undo the catch-all, delete `custom/http.conf` and reload.
|
|
||||||
|
|
||||||
### Plain nginx
|
|
||||||
|
|
||||||
Same idea: remove any existing `default_server` (on Debian/Ubuntu often
|
|
||||||
`sites-enabled/default`) and add
|
|
||||||
|
|
||||||
```nginx
|
```nginx
|
||||||
server {
|
server {
|
||||||
@@ -200,7 +77,7 @@ server {
|
|||||||
server_name _;
|
server_name _;
|
||||||
|
|
||||||
location / {
|
location / {
|
||||||
proxy_pass http://127.0.0.1:8080; # or a variable + resolver for a Docker name, see above
|
proxy_pass http://127.0.0.1:8080;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
proxy_set_header X-Real-IP $remote_addr;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
@@ -210,132 +87,47 @@ server {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
With Flypaper on the same host, `TrustedProxies` can stay empty: loopback is trusted by default.
|
Nginx Proxy Manager, Caddy and Traefik: [docs/reverse-proxy.md](docs/reverse-proxy.md).
|
||||||
|
|
||||||
### Caddy
|
|
||||||
|
|
||||||
```caddyfile
|
|
||||||
# Catch-all for every host on port 80 without its own site block
|
|
||||||
:80 {
|
|
||||||
reverse_proxy flypaper:8080 {
|
|
||||||
header_up X-Real-IP {remote_host}
|
|
||||||
flush_interval -1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# Optional trap paths on a real site
|
|
||||||
example.com {
|
|
||||||
@trap path /.env /.git/* /wp-login.php /xmlrpc.php
|
|
||||||
reverse_proxy @trap flypaper:8080 {
|
|
||||||
header_up X-Real-IP {remote_host}
|
|
||||||
flush_interval -1
|
|
||||||
}
|
|
||||||
reverse_proxy your-app:8080
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Traefik
|
|
||||||
|
|
||||||
Traefik sets `X-Real-Ip` and `X-Forwarded-For` by default. Labels on the Flypaper container
|
|
||||||
(Traefik v3):
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
labels:
|
|
||||||
traefik.enable: "true"
|
|
||||||
# Lowest priority: matches only hosts no other router claims
|
|
||||||
traefik.http.routers.flypaper-catchall.rule: "HostRegexp(`.+`)"
|
|
||||||
traefik.http.routers.flypaper-catchall.entrypoints: web
|
|
||||||
traefik.http.routers.flypaper-catchall.priority: "1"
|
|
||||||
# Optional trap paths on a real site
|
|
||||||
traefik.http.routers.flypaper-bait.rule: "Host(`example.com`) && (Path(`/.env`) || PathPrefix(`/.git/`) || Path(`/wp-login.php`))"
|
|
||||||
traefik.http.routers.flypaper-bait.priority: "1000"
|
|
||||||
traefik.http.services.flypaper.loadbalancer.server.port: "8080"
|
|
||||||
```
|
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
### Environment variables
|
Nothing is required. The most useful optional environment variables:
|
||||||
|
|
||||||
Read at startup. List entries need an index (`__0`, `__1`, ...).
|
| Variable | Purpose |
|
||||||
|
|
||||||
| Variable | Purpose | Default |
|
|
||||||
|---|---|---|
|
|
||||||
| `Flypaper__Http__KnownHosts__0` | Host names that reach the dashboard (`*.example.com` allowed). Every other host is trapped. | none |
|
|
||||||
| `Flypaper__Http__TrustedProxies__0` | IP or CIDR of the reverse proxy allowed to set `X-Real-IP` / `X-Forwarded-For` | loopback only |
|
|
||||||
| `Flypaper__Admin__Password` | Dashboard password. Without it the dashboard stays locked. | none |
|
|
||||||
| `ConnectionStrings__Flypaper` | SQLite database | `Data Source=/data/flypaper.db` |
|
|
||||||
| `Flypaper__DataProtection__KeysPath` | Keys for login cookies and forms | `/data/keys` |
|
|
||||||
| `Flypaper__GeoIp__Directory` | Folder for the DB-IP databases; empty disables GeoIP | `/data/geoip` |
|
|
||||||
| `Flypaper__Drip__MinDelay` / `MaxDelay` | Pause between chunks | `00:00:00.05` / `00:00:01` |
|
|
||||||
| `Flypaper__Drip__MinChunkSize` / `MaxChunkSize` | Bytes per chunk | `1` / `64` |
|
|
||||||
| `TZ` | Time zone for the dashboard | UTC |
|
|
||||||
|
|
||||||
The defaults of the runtime settings below can also be set this way, e.g.
|
|
||||||
`Flypaper__MaxConnections`. Values saved on the settings page override them.
|
|
||||||
|
|
||||||
### Runtime settings
|
|
||||||
|
|
||||||
Changed on the dashboard's settings page, stored in the database, effective immediately. The
|
|
||||||
reset button removes all saved values.
|
|
||||||
|
|
||||||
| Setting | Default |
|
|
||||||
|---|---|
|
|---|---|
|
||||||
| Trap paths (exact, or prefix with a trailing `*`) | `/.env`, `/.env.*`, `/.git/*`, `/.aws/*`, `/.DS_Store`, `/wp-login.php`, `/wp-admin/*`, `/xmlrpc.php`, `/phpmyadmin/*`, `/vendor/phpunit/*`, `/server-status`, `/actuator/*`, `/cgi-bin/*`, `/boaform/*` |
|
| `Flypaper__Admin__Password` | Fixes the dashboard password instead of setting it on first visit |
|
||||||
| Extra known hosts (merged with `KnownHosts`) | none |
|
| `Flypaper__Http__TrustedProxies__0` | Proxy IP or CIDR allowed to set `X-Real-IP` (default: private networks) |
|
||||||
| Maximum hold time per catch | `01:00:00` |
|
| `TZ` | Time zone for the dashboard |
|
||||||
| Maximum connections overall | `1000` |
|
|
||||||
| Maximum connections per IP | `10` |
|
|
||||||
| Keep catches (days, `0` = forever) | `90` |
|
|
||||||
| Don't store catches from private networks | on |
|
|
||||||
|
|
||||||
## Security notes
|
Hold method, limits and retention are changed on the dashboard's settings page. All variables
|
||||||
|
and settings: [docs/configuration.md](docs/configuration.md).
|
||||||
|
|
||||||
- **Keep the dashboard internal.** Only list internal names or LAN addresses as known hosts
|
## Security
|
||||||
and never route a known host through your public proxy.
|
|
||||||
- **Use a strong admin password.** The login runs over plain HTTP unless you put the
|
- Keep the dashboard port `8081` internal; never forward it from your public proxy.
|
||||||
dashboard behind TLS yourself.
|
- Set the admin password right after the first start: until then, anyone who reaches the
|
||||||
- **The limits protect you, not the bots.** Every catch holds a socket in Flypaper and in your
|
dashboard can set it.
|
||||||
proxy for up to the maximum hold time. Keep `MaxConnections` well below what your proxy can
|
- The limits protect your own bandwidth and sockets, keep them below what your proxy can
|
||||||
handle (nginx: `worker_connections`), and keep the per-IP limit low so a single scanner
|
handle.
|
||||||
can't fill all slots.
|
|
||||||
- **An HTTPS catch-all is rarely worth it.** Scanners of unknown hosts mostly speak plain
|
|
||||||
HTTP to the bare IP, and an HTTPS catch-all would need a certificate for names you don't
|
|
||||||
own. Let the proxy reject unknown TLS handshakes instead (nginx: `ssl_reject_handshake on;`).
|
|
||||||
- **Privacy.** Flypaper stores IP addresses, requested URLs and user agents. Keep retention
|
|
||||||
short if that matters in your jurisdiction.
|
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
Requires the .NET 10 SDK.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
dotnet build
|
dotnet build # .NET 10 SDK
|
||||||
dotnet test
|
dotnet test
|
||||||
dotnet run --project src/Flypaper.Web
|
dotnet run --project src/Flypaper.Web # dashboard :5248 (password "dev"), trap :5247
|
||||||
```
|
```
|
||||||
|
|
||||||
`dotnet run` starts in the Development environment: the dashboard is at
|
Details and project layout: [docs/development.md](docs/development.md).
|
||||||
<http://localhost:5248> (known host `localhost`, password `dev`), the database is
|
|
||||||
`src/Flypaper.Web/flypaper.db`, and GeoIP is off unless `Flypaper__GeoIp__Directory` is set.
|
|
||||||
`docker build -t flypaper .` builds the image.
|
|
||||||
|
|
||||||
| Project | Contents |
|
## Versions
|
||||||
|---|---|
|
|
||||||
| `Flypaper.Core` | Protocol-independent core: sessions, governor, strategies, settings |
|
|
||||||
| `Flypaper.Http` | ASP.NET Core middleware, trap matching, forwarded headers |
|
|
||||||
| `Flypaper.GeoIp` | DB-IP download and lookups |
|
|
||||||
| `Flypaper.Storage` | EF Core with SQLite, event writer, retention, dashboard queries |
|
|
||||||
| `Flypaper.Web` | Host, dashboard and settings (Blazor static SSR) |
|
|
||||||
| `Flypaper.Tests` | xUnit, NSubstitute, Shouldly |
|
|
||||||
|
|
||||||
## Attribution
|
Use `:latest` for the newest release or pin `:X.Y.Z`; changes are listed in
|
||||||
|
[CHANGELOG.md](CHANGELOG.md), tags and updates in [docs/releases.md](docs/releases.md). The
|
||||||
|
author's own Unraid deployment lives in [`deploy/unraid/`](deploy/unraid).
|
||||||
|
|
||||||
- [IP Geolocation by DB-IP](https://db-ip.com), licensed under
|
## Attribution and license
|
||||||
[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). The dashboard shows this
|
|
||||||
attribution in its footer.
|
|
||||||
- The world map is generated from [Natural Earth](https://www.naturalearthdata.com) data
|
|
||||||
(public domain).
|
|
||||||
|
|
||||||
## License
|
[IP Geolocation by DB-IP](https://db-ip.com) ([CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)),
|
||||||
|
world map from [Natural Earth](https://www.naturalearthdata.com) (public domain). Flypaper is
|
||||||
[MIT](LICENSE). Third-party data keeps its own license (see *Attribution*).
|
[MIT](LICENSE) licensed; third-party data keeps its own license.
|
||||||
+36
-9
@@ -5,9 +5,35 @@ describes a generic installation.
|
|||||||
|
|
||||||
Every push to `main` (except docs and `.md` files) runs `.gitea/workflows/deploy.yml` on the
|
Every push to `main` (except docs and `.md` files) runs `.gitea/workflows/deploy.yml` on the
|
||||||
act_runner on Unraid: it builds the image, pushes it to
|
act_runner on Unraid: it builds the image, pushes it to
|
||||||
`gitea.anticarnist.de/tom/flypaper` (`:latest` and `:<short-sha>`), deploys
|
`gitea.anticarnist.de/tom/flypaper` (`:main` and `:<short-sha>`), deploys
|
||||||
`deploy/unraid/compose.yaml` and waits for `/health`. A manual run is possible from the Actions
|
`deploy/unraid/compose.yaml` and waits for `/health`. A manual run is possible from the Actions
|
||||||
tab (`workflow_dispatch`).
|
tab (`workflow_dispatch`). The stack follows `:main`, not the releases.
|
||||||
|
|
||||||
|
## Releases
|
||||||
|
|
||||||
|
A version tag runs `.gitea/workflows/release.yml`: it builds the image with that version,
|
||||||
|
pushes `:X.Y.Z`, `:X.Y`, `:X` and `:latest` (a pre-release such as `v0.2.0-rc.1` gets only
|
||||||
|
its own tag) and creates a Gitea release with the version's section of `CHANGELOG.md` as
|
||||||
|
notes. Nothing is deployed.
|
||||||
|
|
||||||
|
1. Move the entries under `[Unreleased]` in `CHANGELOG.md` into a new version section with
|
||||||
|
today's date, update the links at the bottom, commit and push.
|
||||||
|
2. Tag and push:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git tag -a v0.1.0 -m "Flypaper 0.1.0"
|
||||||
|
git push origin v0.1.0
|
||||||
|
```
|
||||||
|
|
||||||
|
The registry serves the images to anyone because the `Tom` account is public; packages
|
||||||
|
inherit the visibility of their owner, not of the repository. To show the package on the
|
||||||
|
repository page, link it once: Gitea → Tom → Packages → `flypaper` → Settings → Link to
|
||||||
|
repository `Flypaper` (or `POST /api/v1/packages/Tom/container/flypaper/-/link/Flypaper` with
|
||||||
|
a token that has `write:package`).
|
||||||
|
|
||||||
|
If the release step fails (e.g. the built-in token may not create releases), the images are
|
||||||
|
already pushed. Create the release by hand: Gitea → repo → Releases → New Release, pick the
|
||||||
|
tag, title `Flypaper X.Y.Z`, paste the changelog section.
|
||||||
|
|
||||||
## Secrets
|
## Secrets
|
||||||
|
|
||||||
@@ -32,13 +58,14 @@ deploy.
|
|||||||
|
|
||||||
## Access
|
## Access
|
||||||
|
|
||||||
- Dashboard: `http://192.168.1.14:44307` (LAN only, login with `FLYPAPER_ADMIN_PASSWORD`)
|
- Dashboard: `http://192.168.1.14:44307` → container port `8081` (LAN only, login with
|
||||||
- Trap: NPM forwards to `flypaper:8080` over `proxynet`. Every Host header other than the
|
`FLYPAPER_ADMIN_PASSWORD`)
|
||||||
dashboard host lands in the trap, as do the trap paths on known hosts.
|
- Trap: NPM forwards to `flypaper:8080` over `proxynet`. Everything on that port is
|
||||||
- `/health` answers only to private addresses; from public addresses it is a trap like any
|
trapped.
|
||||||
other path.
|
- `/health` on `8080` answers only to private addresses; from public addresses it is a trap
|
||||||
|
like any other path. On `8081` it always answers.
|
||||||
|
|
||||||
## Rollback
|
## Rollback
|
||||||
|
|
||||||
Pin the image in `compose.yaml` to a previous `:<short-sha>` and push, or deploy that tag
|
Pin the image in `compose.yaml` to a previous `:<short-sha>` or a release `:X.Y.Z` and push,
|
||||||
manually on Unraid.
|
or deploy that tag manually on Unraid.
|
||||||
@@ -3,8 +3,8 @@
|
|||||||
# .gitea/workflows/deploy.yml, not pasted into the Compose Manager.
|
# .gitea/workflows/deploy.yml, not pasted into the Compose Manager.
|
||||||
#
|
#
|
||||||
# NPM reaches the trap as flypaper:8080 over the external network proxynet (default
|
# NPM reaches the trap as flypaper:8080 over the external network proxynet (default
|
||||||
# site for unknown hosts, trap paths on the real domains). The dashboard is reached
|
# site for unknown hosts). The dashboard has its own
|
||||||
# from the LAN on the host port: http://192.168.1.14:44307.
|
# port 8081, published only to the LAN: http://192.168.1.14:44307.
|
||||||
#
|
#
|
||||||
# `restart: always`, not `unless-stopped`: Unraid stops every container explicitly
|
# `restart: always`, not `unless-stopped`: Unraid stops every container explicitly
|
||||||
# when Docker or the array goes down, and `unless-stopped` treats that as a manual
|
# when Docker or the array goes down, and `unless-stopped` treats that as a manual
|
||||||
@@ -14,15 +14,14 @@ name: flypaper
|
|||||||
|
|
||||||
services:
|
services:
|
||||||
flypaper:
|
flypaper:
|
||||||
image: gitea.anticarnist.de/tom/flypaper:latest
|
# :main follows every push to main; releases are tagged :X.Y.Z and :latest.
|
||||||
|
image: gitea.anticarnist.de/tom/flypaper:main
|
||||||
container_name: flypaper
|
container_name: flypaper
|
||||||
restart: always
|
restart: always
|
||||||
ports:
|
ports:
|
||||||
- "44307:8080"
|
- "44307:8081"
|
||||||
environment:
|
environment:
|
||||||
TZ: Europe/Berlin
|
TZ: Europe/Berlin
|
||||||
# The dashboard host. Every other Host header lands in the trap.
|
|
||||||
Flypaper__Http__KnownHosts__0: 192.168.1.14
|
|
||||||
# Subnet of proxynet: only NPM may set X-Forwarded-For / X-Real-IP.
|
# Subnet of proxynet: only NPM may set X-Forwarded-For / X-Real-IP.
|
||||||
Flypaper__Http__TrustedProxies__0: 172.19.0.0/16
|
Flypaper__Http__TrustedProxies__0: 172.19.0.0/16
|
||||||
# From the repository secret, never in the repo.
|
# From the repository secret, never in the repo.
|
||||||
@@ -34,9 +33,9 @@ services:
|
|||||||
networks:
|
networks:
|
||||||
- proxynet
|
- proxynet
|
||||||
healthcheck:
|
healthcheck:
|
||||||
# The image has neither curl nor wget; bash's /dev/tcp does the request.
|
# The image has neither curl nor wget; bash's /dev/tcp does the request
|
||||||
# /health from loopback is exempt from the trap.
|
# against the dashboard port.
|
||||||
test: ["CMD", "bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/8080 && printf 'GET /health HTTP/1.0\\r\\nHost: localhost\\r\\n\\r\\n' >&3 && head -n 1 <&3 | grep -q ' 200 '"]
|
test: ["CMD", "bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/8081 && printf 'GET /health HTTP/1.0\\r\\nHost: localhost\\r\\n\\r\\n' >&3 && head -n 1 <&3 | grep -q ' 200 '"]
|
||||||
interval: 30s
|
interval: 30s
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
start_period: 10s
|
start_period: 10s
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Started as root (e.g. by the Unraid template): hand /data to the app user, which a
|
||||||
|
# freshly created host folder is not, then drop privileges for good.
|
||||||
|
if [ "$(id -u)" = "0" ]; then
|
||||||
|
chown -R "$APP_UID:$APP_UID" /data
|
||||||
|
exec setpriv --reuid="$APP_UID" --regid="$APP_UID" --clear-groups dotnet /app/Flypaper.Web.dll "$@"
|
||||||
|
fi
|
||||||
|
|
||||||
|
exec dotnet /app/Flypaper.Web.dll "$@"
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# Configuration
|
||||||
|
|
||||||
|
## Data volume
|
||||||
|
|
||||||
|
The container runs as a non-root user (UID 1654) and keeps everything under `/data`: the SQLite
|
||||||
|
database, the Data Protection keys for logins and the GeoIP databases. A named volume gets
|
||||||
|
the right owner automatically; for a bind mount, `chown 1654:1654` the host folder first (or
|
||||||
|
start the container as root once, as the [Unraid template](unraid.md) does).
|
||||||
|
|
||||||
|
## Environment variables
|
||||||
|
|
||||||
|
All optional. Read at startup; list entries need an index (`__0`, `__1`, ...).
|
||||||
|
|
||||||
|
| Variable | Purpose | Default |
|
||||||
|
|---|---|---|
|
||||||
|
| `Flypaper__Admin__Password` | Fixes the dashboard password and disables the first-visit setup and the password change | set on first visit |
|
||||||
|
| `Flypaper__Http__TrustedProxies__0` | IP or CIDR of the reverse proxy allowed to set `X-Real-IP` / `X-Forwarded-For`; replaces the default | private networks |
|
||||||
|
| `Flypaper__Mcp__Token` | Fixed bearer token for the [MCP endpoint](mcp.md), in addition to tokens created on the settings page | none |
|
||||||
|
| `Flypaper__Ports__Trap` / `Flypaper__Ports__Dashboard` | Container ports | `8080` / `8081` |
|
||||||
|
| `ConnectionStrings__Flypaper` | SQLite database | `Data Source=/data/flypaper.db` |
|
||||||
|
| `Flypaper__DataProtection__KeysPath` | Keys for login cookies and forms | `/data/keys` |
|
||||||
|
| `Flypaper__GeoIp__Directory` | Folder for the DB-IP databases; empty disables GeoIP | `/data/geoip` |
|
||||||
|
| `Flypaper__Drip__Content` | Hold method: `Html`, `Text` or `Alternating` | `Html` |
|
||||||
|
| `Flypaper__Drip__MinDelay` / `MaxDelay` | Pause between chunks | `00:00:00.05` / `00:00:01` |
|
||||||
|
| `Flypaper__Drip__MinChunkSize` / `MaxChunkSize` | Bytes per chunk | `1` / `64` |
|
||||||
|
| `TZ` | Time zone for the dashboard | UTC |
|
||||||
|
|
||||||
|
The defaults of the runtime settings below can also be set this way, e.g.
|
||||||
|
`Flypaper__MaxConnections`. Values saved on the settings page override them.
|
||||||
|
|
||||||
|
## Runtime settings
|
||||||
|
|
||||||
|
Changed on the dashboard's settings page, stored in the database, effective immediately. The
|
||||||
|
general reset button removes all saved values; the hold method section has its own reset.
|
||||||
|
|
||||||
|
| Setting | Default |
|
||||||
|
|---|---|
|
||||||
|
| Hold method: content (HTML filler text, random plain text, or alternating per catch) | HTML filler text |
|
||||||
|
| Hold method: pause between chunks, min and max (10 ms to 30 s) | 50 ms / 1000 ms |
|
||||||
|
| Hold method: chunk size, min and max (1 to 4096 bytes) | 1 / 64 bytes |
|
||||||
|
| Hold method: maximum hold time per catch | `01:00:00` |
|
||||||
|
| Maximum connections overall | `1000` |
|
||||||
|
| Maximum connections per IP | `10` |
|
||||||
|
| Keep catches (days, `0` = forever) | `90` |
|
||||||
|
| Don't store catches from private networks | on |
|
||||||
|
|
||||||
|
## Security and privacy
|
||||||
|
|
||||||
|
- **Keep the dashboard internal.** Publish port `8081` only to your LAN or to localhost and
|
||||||
|
never forward it from your public proxy.
|
||||||
|
- **Finish the setup before the dashboard is reachable by anyone else.** Until a password is
|
||||||
|
set, whoever opens the dashboard first can set it. The setup page disappears once a password
|
||||||
|
exists.
|
||||||
|
- **Use a strong admin password** (at least 12 characters). Only a salted hash is stored. The
|
||||||
|
login runs over plain HTTP unless you put the dashboard behind TLS yourself.
|
||||||
|
- **The limits protect you, not the bots.** Every catch holds a socket in Flypaper and in your
|
||||||
|
proxy for up to the maximum hold time. Keep `MaxConnections` well below what your proxy can
|
||||||
|
handle (nginx: `worker_connections`), and keep the per-IP limit low so a single scanner
|
||||||
|
can't fill all slots.
|
||||||
|
- **An HTTPS catch-all is rarely worth it**, see [reverse proxy](reverse-proxy.md#what-to-send-to-flypaper).
|
||||||
|
- **Privacy.** Flypaper stores IP addresses, requested URLs and user agents. Keep retention
|
||||||
|
short if that matters in your jurisdiction.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# Development
|
||||||
|
|
||||||
|
Requires the .NET 10 SDK.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dotnet build
|
||||||
|
dotnet test
|
||||||
|
dotnet run --project src/Flypaper.Web
|
||||||
|
```
|
||||||
|
|
||||||
|
`dotnet run` starts in the Development environment: the dashboard is at
|
||||||
|
<http://localhost:5248> (password `dev`), the trap at <http://localhost:5247>, the database is
|
||||||
|
`src/Flypaper.Web/flypaper.db`, and GeoIP is off unless `Flypaper__GeoIp__Directory` is set.
|
||||||
|
`docker build -t flypaper .` builds the image.
|
||||||
|
|
||||||
|
| Project | Contents |
|
||||||
|
|---|---|
|
||||||
|
| `Flypaper.Core` | Protocol-independent core: sessions, governor, strategies, settings |
|
||||||
|
| `Flypaper.Http` | ASP.NET Core middleware, trap matching, forwarded headers |
|
||||||
|
| `Flypaper.GeoIp` | DB-IP download and lookups |
|
||||||
|
| `Flypaper.Storage` | EF Core with SQLite, event writer, retention, dashboard queries |
|
||||||
|
| `Flypaper.Web` | Host, dashboard and settings (Blazor static SSR) |
|
||||||
|
| `Flypaper.Tests` | xUnit, NSubstitute, Shouldly |
|
||||||
|
|
||||||
|
The files in [`deploy/unraid/`](../deploy/unraid) and `.gitea/workflows/` are the author's
|
||||||
|
personal deployment (Gitea Actions to Unraid) and release pipeline. They are an example only and
|
||||||
|
not needed to run Flypaper.
|
||||||
+71
@@ -0,0 +1,71 @@
|
|||||||
|
# MCP access for AI assistants
|
||||||
|
|
||||||
|
Flypaper includes a [Model Context Protocol](https://modelcontextprotocol.io) server, so AI
|
||||||
|
assistants such as Claude can query your catches: "Which countries hit the trap most this week?",
|
||||||
|
"What do we know about 203.0.113.9?". All tools only read; nothing can be changed or deleted
|
||||||
|
over MCP.
|
||||||
|
|
||||||
|
- Endpoint: `http://<host>:8081/mcp` (Streamable HTTP, dashboard port only; on the trap port
|
||||||
|
`8080` the path is just another trap)
|
||||||
|
- Authentication: `Authorization: Bearer <token>`; without a valid token the answer is `401`
|
||||||
|
|
||||||
|
**LAN only.** The MCP endpoint lives on the dashboard port and must stay as internal as the
|
||||||
|
dashboard: never forward port `8081` from your public proxy.
|
||||||
|
|
||||||
|
## Create a token
|
||||||
|
|
||||||
|
Dashboard → **Einstellungen** → **MCP-Zugriff**: enter a name (e.g. *Claude Code*) and create
|
||||||
|
the token. It is shown exactly once, so copy it right away; Flypaper stores only its SHA-256
|
||||||
|
hash. The list shows each token's name, creation date and last use, and lets you revoke it.
|
||||||
|
|
||||||
|
Alternatively, set a fixed token with the environment variable `Flypaper__Mcp__Token` (useful
|
||||||
|
for automated setups). It works in addition to the tokens created in the dashboard.
|
||||||
|
|
||||||
|
## Connect Claude Code
|
||||||
|
|
||||||
|
```bash
|
||||||
|
claude mcp add --transport http flypaper http://192.168.1.10:8081/mcp \
|
||||||
|
--header "Authorization: Bearer fpm_your_token"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Connect Claude Desktop
|
||||||
|
|
||||||
|
Claude Desktop's custom connectors are reached from Anthropic's cloud and can't see your LAN.
|
||||||
|
Use the local [`mcp-remote`](https://www.npmjs.com/package/mcp-remote) bridge instead (needs
|
||||||
|
Node.js), in `claude_desktop_config.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"flypaper": {
|
||||||
|
"command": "npx",
|
||||||
|
"args": [
|
||||||
|
"mcp-remote",
|
||||||
|
"http://192.168.1.10:8081/mcp",
|
||||||
|
"--allow-http",
|
||||||
|
"--header",
|
||||||
|
"Authorization: Bearer ${FLYPAPER_TOKEN}"
|
||||||
|
],
|
||||||
|
"env": { "FLYPAPER_TOKEN": "fpm_your_token" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`--allow-http` is needed because the dashboard port speaks plain HTTP.
|
||||||
|
|
||||||
|
## Tools
|
||||||
|
|
||||||
|
All tools return structured JSON (with an output schema); times are ISO 8601 UTC, durations in
|
||||||
|
seconds. A *period* is a number with `m`, `h`, `d` or `w` (e.g. `1h`, `24h`, `7d`) or `all`.
|
||||||
|
|
||||||
|
| Tool | Parameters | Returns |
|
||||||
|
|---|---|---|
|
||||||
|
| `get_stats` | `period` (default `24h`) | Catches, rejected connections, unique IPs, total and average hold time, traps active now, longest catch |
|
||||||
|
| `list_catches` | `since`, `until` (ISO 8601), `country` (ISO code), `provider` (`AS4134` or part of the name), `ip`, `target_contains`, `limit` (default 50, max 500) | Events, newest first, including rejected ones |
|
||||||
|
| `top` | `dimension` (`ips`, `countries`, `providers`, `targets`, `user_agents`), `period` (default `24h`), `limit` (default 10) | Most frequent values by number of catches, with total hold time |
|
||||||
|
| `longest_catches` | `period` (default `7d`), `limit` (default 10) | Catches that held a bot the longest |
|
||||||
|
| `lookup_ip` | `ip` | Origin, provider, totals, first and last seen, and its events (newest first, at most 500); local data only |
|
||||||
|
|
||||||
|
Catches from private networks appear only if they are stored, i.e. if the setting *Fänge aus
|
||||||
|
privaten Netzen nicht speichern* is off.
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
# How Flypaper works
|
||||||
|
|
||||||
|
Every server on the internet gets a steady stream of bots probing for `/.env`, `/.git/config`,
|
||||||
|
`/wp-login.php` and friends, usually sent to the bare IP address or to host names that don't
|
||||||
|
exist. Blocklists play whack-a-mole with addresses that change daily. Flypaper takes the
|
||||||
|
opposite approach: it lets the bot in and then answers very, very slowly. While a scanner waits
|
||||||
|
for an endless HTML page that trickles in a few bytes at a time, it isn't scanning someone
|
||||||
|
else, and every catch is logged with its origin for you to look at.
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
bot["Scanner bot"] -->|"GET /.env<br/>Host: 203.0.113.7"| proxy["Reverse proxy"]
|
||||||
|
proxy -->|"known site"| apps["Your apps"]
|
||||||
|
proxy -->|"unknown host<br/>+ X-Real-IP"| flypaper["Flypaper"]
|
||||||
|
flypaper -.->|"endless HTML,<br/>a few bytes at a time"| bot
|
||||||
|
flypaper --> db[("SQLite:<br/>catches, settings")]
|
||||||
|
you["You (LAN)"] -->|"dashboard, port 8081"| flypaper
|
||||||
|
```
|
||||||
|
|
||||||
|
1. Your reverse proxy keeps serving your real sites. Everything it has no site for (the
|
||||||
|
default/catch-all server) goes to Flypaper.
|
||||||
|
2. Flypaper listens on two ports. Port `8080` is the trap: everything that arrives there is
|
||||||
|
caught. Port `8081` serves the dashboard and never traps; keep it inside your LAN.
|
||||||
|
3. A caught request gets `200 OK` and an endless, plausible-looking HTML page: random chunks
|
||||||
|
of 1 to 64 bytes with random pauses of 50 ms to 1 s in between.
|
||||||
|
4. A connection governor caps the number of catches overall and per IP and ends every catch
|
||||||
|
after a maximum hold time. If there is no free slot, the request gets a quick `404`.
|
||||||
|
5. When a catch ends, Flypaper logs one line and stores the event in SQLite, enriched with
|
||||||
|
country, city and network provider (ASN) from the free DB-IP databases.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- **Trap** for everything that reaches the trap port: whatever host or path a bot asks for
|
||||||
|
- **Slow delivery** of endless generated HTML or plain text (or both, alternating per catch)
|
||||||
|
with irregular timing; content, pauses, chunk sizes and hold time are set in the dashboard
|
||||||
|
- **Limits**: maximum connections overall and per IP, maximum hold time per catch
|
||||||
|
- **Dashboard**: totals, a world map, top countries, providers, IPs and paths, the latest
|
||||||
|
catches with expandable details; login with an admin password
|
||||||
|
- **GeoIP**: country, city and ASN per catch from DB-IP Lite, downloaded and refreshed
|
||||||
|
monthly; existing catches are filled in once the databases are available
|
||||||
|
- **Settings page**: hold method, limits and retention, changed at runtime
|
||||||
|
without a restart
|
||||||
|
- **Retention**: old catches are deleted daily (90 days by default); catches from private
|
||||||
|
networks are not stored by default; buttons to delete private or all catches
|
||||||
|
- **One log line per catch**, so `docker logs` alone shows whether the trap works
|
||||||
|
- **MCP server** on the dashboard port, so AI assistants can query the catches read-only
|
||||||
|
([docs/mcp.md](mcp.md))
|
||||||
|
- **Health endpoint** `/health` for container health checks (on the trap port it answers only
|
||||||
|
to private addresses)
|
||||||
|
- **No configuration needed to start**: one volume, two ports, the admin password is set on
|
||||||
|
first visit
|
||||||
|
|
||||||
|
## Trying the trap locally
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -N http://localhost:8080/
|
||||||
|
```
|
||||||
|
|
||||||
|
This catch comes from a private address and is therefore not stored; the log line ends with
|
||||||
|
`(not stored)`.
|
||||||
|
|
||||||
|
## Attribution
|
||||||
|
|
||||||
|
Origins come from [IP Geolocation by DB-IP](https://db-ip.com), licensed under
|
||||||
|
[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/); the dashboard shows this attribution
|
||||||
|
in its footer. The world map is generated from [Natural Earth](https://www.naturalearthdata.com)
|
||||||
|
data (public domain).
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# Versions, images and updates
|
||||||
|
|
||||||
|
Flypaper follows [Semantic Versioning](https://semver.org); every release is listed in
|
||||||
|
[CHANGELOG.md](../CHANGELOG.md) and on the
|
||||||
|
[releases page](https://gitea.anticarnist.de/Tom/Flypaper/releases). The running version is
|
||||||
|
shown in the dashboard footer and in the first log line.
|
||||||
|
|
||||||
|
All images live at `gitea.anticarnist.de/tom/flypaper`
|
||||||
|
([package page](https://gitea.anticarnist.de/Tom/-/packages/container/flypaper/latest)); no
|
||||||
|
login is needed to pull.
|
||||||
|
|
||||||
|
| Image tag | Meaning | Platforms |
|
||||||
|
|---|---|---|
|
||||||
|
| `:latest` | The newest release. The right choice for most setups. | amd64, arm64 |
|
||||||
|
| `:X.Y.Z` | A fixed release, e.g. `:0.1.0`. Pin it if you update deliberately. | amd64, arm64 |
|
||||||
|
| `:X.Y`, `:X` | The newest release of that minor or major line, e.g. `:0.1`, `:0`. | amd64, arm64 |
|
||||||
|
| `:main` | Development build of the latest commit on `main`. May break. | amd64 |
|
||||||
|
| `:<sha>` | Development build of one commit (short SHA), e.g. for a rollback. | amd64 |
|
||||||
|
|
||||||
|
arm64 covers e.g. a Raspberry Pi 4/5 with a 64-bit OS.
|
||||||
|
|
||||||
|
Pull a fixed version with `docker pull gitea.anticarnist.de/tom/flypaper:0.1.0`. To build a
|
||||||
|
specific release from source instead:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git checkout v0.1.0
|
||||||
|
docker build --build-arg VERSION=0.1.0 -t flypaper:0.1.0 .
|
||||||
|
```
|
||||||
|
|
||||||
|
You can always build the current source yourself: clone the repository and replace the
|
||||||
|
`image:` line in your compose file with `build: .`, or run `docker build -t flypaper .`.
|
||||||
|
|
||||||
|
## Updating
|
||||||
|
|
||||||
|
Pull or rebuild the image and recreate the container
|
||||||
|
(`docker compose pull && docker compose up -d`). The database is migrated automatically on
|
||||||
|
start; back up the `/data` volume first. Before 1.0, a minor version may contain breaking
|
||||||
|
changes, so read the changelog.
|
||||||
|
|
||||||
|
How releases are cut is described in [`deploy/unraid/README.md`](../deploy/unraid/README.md#releases).
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
# Behind a reverse proxy
|
||||||
|
|
||||||
|
Flypaper is meant to sit behind the reverse proxy that already owns ports 80/443. The proxy
|
||||||
|
forwards to the trap port `8080`; the dashboard port `8081` is never forwarded. Two rules
|
||||||
|
apply to every proxy:
|
||||||
|
|
||||||
|
- **Set `X-Real-IP`** (and `X-Forwarded-For`) to the client address.
|
||||||
|
- **Flypaper must trust the proxy.** By default it trusts every private network (`10/8`,
|
||||||
|
`172.16/12`, `192.168/16`, loopback, `fc00::/7`), which covers a proxy in a Docker network
|
||||||
|
or on the LAN. Headers from public addresses are ignored, so bots can't fake their address.
|
||||||
|
To narrow it down, set `Flypaper__Http__TrustedProxies__0` to the proxy's IP or subnet, e.g.
|
||||||
|
the Docker network's subnet:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker network inspect <network> -f '{{(index .IPAM.Config 0).Subnet}}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Also turn off response buffering for Flypaper, otherwise the proxy collects the drip and the
|
||||||
|
bot never sees it. Flypaper sends `X-Accel-Buffering: no`, which nginx honors.
|
||||||
|
|
||||||
|
## What to send to Flypaper
|
||||||
|
|
||||||
|
Send your proxy's catch-all server to Flypaper: requests for hosts you don't serve (mostly the
|
||||||
|
bare IP). This is where almost all scanners end up. Everything that reaches the trap port is
|
||||||
|
caught, whatever host or path it asks for; the dashboard is never reachable there.
|
||||||
|
|
||||||
|
**An HTTPS catch-all is rarely worth it.** Scanners of unknown hosts mostly speak plain HTTP to
|
||||||
|
the bare IP, and an HTTPS catch-all would need a certificate for names you don't own. Let the
|
||||||
|
proxy reject unknown TLS handshakes instead (nginx: `ssl_reject_handshake on;`).
|
||||||
|
|
||||||
|
## Nginx Proxy Manager
|
||||||
|
|
||||||
|
Put Flypaper into the same Docker network as NPM (the examples use the container name
|
||||||
|
`flypaper`).
|
||||||
|
|
||||||
|
1. **Settings → Default Site → Congratulations Page.** With this setting NPM writes no
|
||||||
|
default server of its own. Any other choice (404, redirect, HTML) creates one, and nginx
|
||||||
|
refuses to start with two default servers.
|
||||||
|
2. Create `/data/nginx/custom/http.conf` in the NPM container (on the host: inside NPM's
|
||||||
|
data volume):
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
# Catch-all: every HTTP request whose Host matches no proxy host goes to Flypaper.
|
||||||
|
server {
|
||||||
|
listen 80 default_server; # the HTTP port NPM listens on inside its container
|
||||||
|
listen [::]:80 default_server;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
# A variable makes nginx resolve the name per request, so NPM still starts
|
||||||
|
# (and serves your sites) while the Flypaper container is down.
|
||||||
|
resolver 127.0.0.11 valid=30s;
|
||||||
|
set $flypaper http://flypaper:8080;
|
||||||
|
proxy_pass $flypaper;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_buffering off;
|
||||||
|
proxy_read_timeout 1h;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Test and reload: `docker exec <npm-container> nginx -t`, then
|
||||||
|
`docker exec <npm-container> nginx -s reload`.
|
||||||
|
To undo the catch-all, delete `custom/http.conf` and reload.
|
||||||
|
|
||||||
|
## Plain nginx
|
||||||
|
|
||||||
|
Remove any existing `default_server` (on Debian/Ubuntu often `sites-enabled/default`) and add
|
||||||
|
|
||||||
|
```nginx
|
||||||
|
server {
|
||||||
|
listen 80 default_server;
|
||||||
|
listen [::]:80 default_server;
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:8080; # or a variable + resolver for a Docker name, see NPM
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_buffering off;
|
||||||
|
proxy_read_timeout 1h;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
With Flypaper on the same host, nothing else is needed: loopback is trusted by default.
|
||||||
|
|
||||||
|
## Caddy
|
||||||
|
|
||||||
|
```caddyfile
|
||||||
|
# Catch-all for every host on port 80 without its own site block
|
||||||
|
:80 {
|
||||||
|
reverse_proxy flypaper:8080 {
|
||||||
|
header_up X-Real-IP {remote_host}
|
||||||
|
flush_interval -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Traefik
|
||||||
|
|
||||||
|
Traefik sets `X-Real-Ip` and `X-Forwarded-For` by default. Labels on the Flypaper container
|
||||||
|
(Traefik v3):
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
labels:
|
||||||
|
traefik.enable: "true"
|
||||||
|
# Lowest priority: matches only hosts no other router claims
|
||||||
|
traefik.http.routers.flypaper-catchall.rule: "HostRegexp(`.+`)"
|
||||||
|
traefik.http.routers.flypaper-catchall.entrypoints: web
|
||||||
|
traefik.http.routers.flypaper-catchall.priority: "1"
|
||||||
|
traefik.http.services.flypaper.loadbalancer.server.port: "8080"
|
||||||
|
```
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Unraid
|
||||||
|
|
||||||
|
[`unraid/flypaper.xml`](../unraid/flypaper.xml) is a Docker template for Unraid. It sets up both
|
||||||
|
ports, the appdata folder `/mnt/user/appdata/flypaper` and the optional variables (under
|
||||||
|
*Show more settings*).
|
||||||
|
|
||||||
|
1. Copy the template to the flash drive, in the Unraid terminal:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
wget -O /boot/config/plugins/dockerMan/templates-user/my-Flypaper.xml \
|
||||||
|
https://gitea.anticarnist.de/Tom/Flypaper/raw/branch/main/unraid/flypaper.xml
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Docker → Add Container**, pick *Flypaper* under the user templates, choose free host ports
|
||||||
|
(8080 is often taken on Unraid) and **Apply**.
|
||||||
|
3. Open the WebUI (the dashboard port) and set the admin password.
|
||||||
|
|
||||||
|
Unraid can also read templates from a *template repository* (Docker tab, Advanced View), but
|
||||||
|
that feature is built around GitHub repositories and may not accept this Gitea URL; the manual
|
||||||
|
copy above always works.
|
||||||
|
|
||||||
|
The template starts the container as root (`--user 0:0`) only so it can hand the appdata folder
|
||||||
|
to its app user; Flypaper then drops to UID 1654 for good. Without it, a freshly created appdata
|
||||||
|
folder belongs to root and the database cannot be created.
|
||||||
|
|
||||||
|
## Connecting Nginx Proxy Manager
|
||||||
|
|
||||||
|
Follow the [NPM section](reverse-proxy.md#nginx-proxy-manager). If NPM runs in a user-defined
|
||||||
|
Docker network (e.g. `proxynet`), put Flypaper into the same network (*Network Type* in the
|
||||||
|
template) and use `http://Flypaper:8080` as the target. If NPM can't share a network with it,
|
||||||
|
forward to `http://<unraid-ip>:<trap-port>` instead. Either way the request comes from a
|
||||||
|
private address, which Flypaper trusts by default.
|
||||||
|
|
||||||
|
The template is not part of the official Community Applications yet; that needs a separate
|
||||||
|
submission.
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace Flypaper.Core.Abstractions;
|
||||||
|
|
||||||
|
public interface IStrategyDetails
|
||||||
|
{
|
||||||
|
string MediaType { get; }
|
||||||
|
|
||||||
|
string Describe();
|
||||||
|
}
|
||||||
@@ -19,7 +19,8 @@ public static class FlypaperCoreExtensions
|
|||||||
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>();
|
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>();
|
||||||
services.TryAddSingleton<IRandomSource, SystemRandomSource>();
|
services.TryAddSingleton<IRandomSource, SystemRandomSource>();
|
||||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>());
|
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>());
|
||||||
services.TryAddSingleton<ITrapStrategySelector, ProtocolStrategySelector>();
|
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, TextDripStrategy>());
|
||||||
|
services.TryAddSingleton<ITrapStrategySelector, ConfiguredStrategySelector>();
|
||||||
services.TryAddSingleton<TrapRunner>();
|
services.TryAddSingleton<TrapRunner>();
|
||||||
services.TryAddSingleton<IIpEnricher, NullIpEnricher>();
|
services.TryAddSingleton<IIpEnricher, NullIpEnricher>();
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
using Flypaper.Core.Abstractions;
|
||||||
|
using Flypaper.Core.Models;
|
||||||
|
using Flypaper.Core.Strategies;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Runtime;
|
||||||
|
|
||||||
|
public sealed class ConfiguredStrategySelector(
|
||||||
|
IEnumerable<ITarpitStrategy> strategies,
|
||||||
|
IOptionsMonitor<DripOptions> options,
|
||||||
|
IRandomSource random) : ITrapStrategySelector
|
||||||
|
{
|
||||||
|
public ITarpitStrategy? Select(TrapContext context)
|
||||||
|
{
|
||||||
|
var candidates = strategies.Where(strategy => strategy.Supports(context.Session.Protocol)).ToList();
|
||||||
|
string[] wanted = options.CurrentValue.Content switch
|
||||||
|
{
|
||||||
|
DripContent.Text => [TextDripStrategy.StrategyName],
|
||||||
|
DripContent.Alternating => [HtmlDripStrategy.StrategyName, TextDripStrategy.StrategyName],
|
||||||
|
_ => [HtmlDripStrategy.StrategyName]
|
||||||
|
};
|
||||||
|
|
||||||
|
var matching = candidates.Where(strategy => wanted.Contains(strategy.Name)).ToList();
|
||||||
|
return matching.Count == 0
|
||||||
|
? candidates.FirstOrDefault()
|
||||||
|
: matching[random.Next(0, matching.Count)];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
using Flypaper.Core.Abstractions;
|
|
||||||
using Flypaper.Core.Models;
|
|
||||||
|
|
||||||
namespace Flypaper.Core.Runtime;
|
|
||||||
|
|
||||||
public sealed class ProtocolStrategySelector(IEnumerable<ITarpitStrategy> strategies) : ITrapStrategySelector
|
|
||||||
{
|
|
||||||
public ITarpitStrategy? Select(TrapContext context) =>
|
|
||||||
strategies.FirstOrDefault(strategy => strategy.Supports(context.Session.Protocol));
|
|
||||||
}
|
|
||||||
@@ -17,7 +17,7 @@ public sealed partial class TrapRunner(
|
|||||||
{
|
{
|
||||||
public async Task<TrapOutcome> RunAsync(
|
public async Task<TrapOutcome> RunAsync(
|
||||||
TrapContext context,
|
TrapContext context,
|
||||||
Func<CancellationToken, ValueTask<ITrapChannel>> openChannel,
|
Func<ITarpitStrategy, CancellationToken, ValueTask<ITrapChannel>> openChannel,
|
||||||
CancellationToken ct)
|
CancellationToken ct)
|
||||||
{
|
{
|
||||||
var session = context.Session;
|
var session = context.Session;
|
||||||
@@ -30,6 +30,7 @@ public sealed partial class TrapRunner(
|
|||||||
}
|
}
|
||||||
|
|
||||||
using var _ = lease;
|
using var _ = lease;
|
||||||
|
var description = strategy is IStrategyDetails details ? details.Describe() : strategy.Name;
|
||||||
using var hold = new CancellationTokenSource(options.CurrentValue.MaxHoldDuration, timeProvider);
|
using var hold = new CancellationTokenSource(options.CurrentValue.MaxHoldDuration, timeProvider);
|
||||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
|
||||||
|
|
||||||
@@ -37,7 +38,7 @@ public sealed partial class TrapRunner(
|
|||||||
var outcome = TrapOutcome.Completed;
|
var outcome = TrapOutcome.Completed;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
channel = new CountingTrapChannel(await openChannel(linked.Token));
|
channel = new CountingTrapChannel(await openChannel(strategy, linked.Token));
|
||||||
await strategy.RunAsync(channel, linked.Token);
|
await strategy.RunAsync(channel, linked.Token);
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException) when (linked.IsCancellationRequested)
|
catch (OperationCanceledException) when (linked.IsCancellationRequested)
|
||||||
@@ -51,7 +52,7 @@ public sealed partial class TrapRunner(
|
|||||||
outcome = TrapOutcome.ClientAborted;
|
outcome = TrapOutcome.ClientAborted;
|
||||||
}
|
}
|
||||||
|
|
||||||
Publish(context, strategy.Name, channel?.BytesSent ?? 0, outcome);
|
Publish(context, description, channel?.BytesSent ?? 0, outcome);
|
||||||
return outcome;
|
return outcome;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Flypaper.Core.Strategies;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Settings;
|
||||||
|
|
||||||
|
public sealed record HoldMethodSettings(
|
||||||
|
DripContent Content,
|
||||||
|
TimeSpan MinDelay,
|
||||||
|
TimeSpan MaxDelay,
|
||||||
|
int MinChunkSize,
|
||||||
|
int MaxChunkSize,
|
||||||
|
TimeSpan MaxHoldDuration)
|
||||||
|
{
|
||||||
|
public double BytesPerSecond => AverageBytesPerSecond(MinDelay, MaxDelay, MinChunkSize, MaxChunkSize);
|
||||||
|
|
||||||
|
public IReadOnlyDictionary<string, string> ToConfiguration() => new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
[SettingKeys.DripContent] = Content.ToString(),
|
||||||
|
[SettingKeys.DripMinDelay] = MinDelay.ToString("c", CultureInfo.InvariantCulture),
|
||||||
|
[SettingKeys.DripMaxDelay] = MaxDelay.ToString("c", CultureInfo.InvariantCulture),
|
||||||
|
[SettingKeys.DripMinChunkSize] = MinChunkSize.ToString(CultureInfo.InvariantCulture),
|
||||||
|
[SettingKeys.DripMaxChunkSize] = MaxChunkSize.ToString(CultureInfo.InvariantCulture),
|
||||||
|
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
|
||||||
|
};
|
||||||
|
|
||||||
|
public static double AverageBytesPerSecond(TimeSpan minDelay, TimeSpan maxDelay, int minChunkSize, int maxChunkSize)
|
||||||
|
{
|
||||||
|
var averageDelay = (minDelay + maxDelay).TotalSeconds / 2;
|
||||||
|
return averageDelay <= 0 ? 0 : (minChunkSize + maxChunkSize) / 2d / averageDelay;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record HoldMethodInput(
|
||||||
|
string? Content,
|
||||||
|
string? MinDelayMs,
|
||||||
|
string? MaxDelayMs,
|
||||||
|
string? MinChunkSize,
|
||||||
|
string? MaxChunkSize,
|
||||||
|
string? MaxHoldDuration);
|
||||||
|
|
||||||
|
public sealed record HoldMethodParseResult(HoldMethodSettings? Settings, IReadOnlyDictionary<string, string> Errors);
|
||||||
@@ -3,21 +3,15 @@ using System.Globalization;
|
|||||||
namespace Flypaper.Core.Settings;
|
namespace Flypaper.Core.Settings;
|
||||||
|
|
||||||
public sealed record RuntimeSettings(
|
public sealed record RuntimeSettings(
|
||||||
IReadOnlyList<string> TrapPaths,
|
|
||||||
int MaxConnections,
|
int MaxConnections,
|
||||||
int MaxConnectionsPerIp,
|
int MaxConnectionsPerIp,
|
||||||
TimeSpan MaxHoldDuration,
|
|
||||||
IReadOnlyList<string> ExtraKnownHosts,
|
|
||||||
int RetentionDays,
|
int RetentionDays,
|
||||||
bool IgnorePrivateNetworks)
|
bool IgnorePrivateNetworks)
|
||||||
{
|
{
|
||||||
public IReadOnlyDictionary<string, string> ToConfiguration() => new Dictionary<string, string>
|
public IReadOnlyDictionary<string, string> ToConfiguration() => new Dictionary<string, string>
|
||||||
{
|
{
|
||||||
[SettingKeys.TrapPaths] = SettingsList.Join(TrapPaths),
|
|
||||||
[SettingKeys.MaxConnections] = MaxConnections.ToString(CultureInfo.InvariantCulture),
|
[SettingKeys.MaxConnections] = MaxConnections.ToString(CultureInfo.InvariantCulture),
|
||||||
[SettingKeys.MaxConnectionsPerIp] = MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
|
[SettingKeys.MaxConnectionsPerIp] = MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
|
||||||
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
|
|
||||||
[SettingKeys.ExtraKnownHosts] = SettingsList.Join(ExtraKnownHosts),
|
|
||||||
[SettingKeys.RetentionDays] = RetentionDays.ToString(CultureInfo.InvariantCulture),
|
[SettingKeys.RetentionDays] = RetentionDays.ToString(CultureInfo.InvariantCulture),
|
||||||
[SettingKeys.IgnorePrivateNetworks] = IgnorePrivateNetworks ? "true" : "false"
|
[SettingKeys.IgnorePrivateNetworks] = IgnorePrivateNetworks ? "true" : "false"
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
namespace Flypaper.Core.Settings;
|
namespace Flypaper.Core.Settings;
|
||||||
|
|
||||||
public sealed record RuntimeSettingsInput(
|
public sealed record RuntimeSettingsInput(
|
||||||
string? TrapPaths,
|
|
||||||
string? MaxConnections,
|
string? MaxConnections,
|
||||||
string? MaxConnectionsPerIp,
|
string? MaxConnectionsPerIp,
|
||||||
string? MaxHoldDuration,
|
|
||||||
string? ExtraKnownHosts,
|
|
||||||
string? RetentionDays,
|
string? RetentionDays,
|
||||||
bool IgnorePrivateNetworks);
|
bool IgnorePrivateNetworks);
|
||||||
@@ -1,29 +1,23 @@
|
|||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Text.RegularExpressions;
|
using Flypaper.Core.Strategies;
|
||||||
|
|
||||||
namespace Flypaper.Core.Settings;
|
namespace Flypaper.Core.Settings;
|
||||||
|
|
||||||
public static partial class RuntimeSettingsParser
|
public static class RuntimeSettingsParser
|
||||||
{
|
{
|
||||||
private const int MaxListEntries = 500;
|
|
||||||
private const int MaxPathLength = 256;
|
|
||||||
private const int MaxHostLength = 253;
|
|
||||||
private const int MaxLimit = 100_000;
|
private const int MaxLimit = 100_000;
|
||||||
private const int MaxRetentionDays = 3650;
|
private const int MaxRetentionDays = 3650;
|
||||||
|
|
||||||
private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1);
|
private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1);
|
||||||
private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7);
|
private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7);
|
||||||
|
private const int MinDelayMs = 10;
|
||||||
[GeneratedRegex(@"^(\*\.)?[A-Za-z0-9]([A-Za-z0-9.\-]*[A-Za-z0-9])?$")]
|
private const int MaxDelayMs = 30_000;
|
||||||
private static partial Regex HostPattern();
|
private const int MaxChunkSize = 4096;
|
||||||
|
|
||||||
public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input)
|
public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input)
|
||||||
{
|
{
|
||||||
var errors = new Dictionary<string, string>();
|
var errors = new Dictionary<string, string>();
|
||||||
|
|
||||||
var paths = ParseList(input.TrapPaths, nameof(input.TrapPaths), ValidatePath, errors);
|
|
||||||
var hosts = ParseList(input.ExtraKnownHosts, nameof(input.ExtraKnownHosts), ValidateHost, errors);
|
|
||||||
var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
|
|
||||||
var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), 1, MaxLimit, errors);
|
var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), 1, MaxLimit, errors);
|
||||||
var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), 1, MaxLimit, errors);
|
var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), 1, MaxLimit, errors);
|
||||||
var retention = ParseInt(input.RetentionDays, nameof(input.RetentionDays), 0, MaxRetentionDays, errors);
|
var retention = ParseInt(input.RetentionDays, nameof(input.RetentionDays), 0, MaxRetentionDays, errors);
|
||||||
@@ -40,78 +34,55 @@ public static partial class RuntimeSettingsParser
|
|||||||
}
|
}
|
||||||
|
|
||||||
var settings = new RuntimeSettings(
|
var settings = new RuntimeSettings(
|
||||||
paths!,
|
|
||||||
maxConnections!.Value,
|
maxConnections!.Value,
|
||||||
perIp!.Value,
|
perIp!.Value,
|
||||||
hold!.Value,
|
|
||||||
hosts!,
|
|
||||||
retention!.Value,
|
retention!.Value,
|
||||||
input.IgnorePrivateNetworks);
|
input.IgnorePrivateNetworks);
|
||||||
return new RuntimeSettingsParseResult(settings, errors);
|
return new RuntimeSettingsParseResult(settings, errors);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string[]? ParseList(
|
public static HoldMethodParseResult ParseHoldMethod(HoldMethodInput input)
|
||||||
string? raw,
|
|
||||||
string field,
|
|
||||||
Func<string, string?> validate,
|
|
||||||
Dictionary<string, string> errors)
|
|
||||||
{
|
{
|
||||||
var lines = (raw ?? string.Empty)
|
var errors = new Dictionary<string, string>();
|
||||||
.Split(['\r', '\n'], StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
|
|
||||||
|
|
||||||
if (lines.Length > MaxListEntries)
|
DripContent? content = Enum.TryParse<DripContent>(input.Content, ignoreCase: true, out var parsed) && Enum.IsDefined(parsed)
|
||||||
|
? parsed
|
||||||
|
: null;
|
||||||
|
if (content is null)
|
||||||
{
|
{
|
||||||
errors[field] = $"Höchstens {MaxListEntries} Einträge.";
|
errors[nameof(input.Content)] = "Bitte eine Methode wählen.";
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var problems = new List<string>();
|
var minDelay = ParseInt(input.MinDelayMs, nameof(input.MinDelayMs), MinDelayMs, MaxDelayMs, errors);
|
||||||
for (var i = 0; i < lines.Length; i++)
|
var maxDelay = ParseInt(input.MaxDelayMs, nameof(input.MaxDelayMs), MinDelayMs, MaxDelayMs, errors);
|
||||||
|
var minChunk = ParseInt(input.MinChunkSize, nameof(input.MinChunkSize), 1, MaxChunkSize, errors);
|
||||||
|
var maxChunk = ParseInt(input.MaxChunkSize, nameof(input.MaxChunkSize), 1, MaxChunkSize, errors);
|
||||||
|
var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
|
||||||
|
|
||||||
|
if (minDelay > maxDelay)
|
||||||
{
|
{
|
||||||
if (validate(lines[i]) is { } problem)
|
errors[nameof(input.MaxDelayMs)] = "Darf nicht kleiner sein als das Minimum.";
|
||||||
{
|
|
||||||
problems.Add($"„{lines[i]}“: {problem}");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (problems.Count > 0)
|
if (minChunk > maxChunk)
|
||||||
{
|
{
|
||||||
errors[field] = string.Join(" ", problems.Take(3)) + (problems.Count > 3 ? $" (+{problems.Count - 3} weitere)" : "");
|
errors[nameof(input.MaxChunkSize)] = "Darf nicht kleiner sein als das Minimum.";
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return lines.Distinct(StringComparer.Ordinal).ToArray();
|
if (errors.Count > 0)
|
||||||
}
|
|
||||||
|
|
||||||
private static string? ValidatePath(string path)
|
|
||||||
{
|
|
||||||
if (path[0] != '/')
|
|
||||||
{
|
{
|
||||||
return "muss mit / beginnen.";
|
return new HoldMethodParseResult(null, errors);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (path.Length > MaxPathLength)
|
return new HoldMethodParseResult(
|
||||||
{
|
new HoldMethodSettings(
|
||||||
return $"höchstens {MaxPathLength} Zeichen.";
|
content!.Value,
|
||||||
}
|
TimeSpan.FromMilliseconds(minDelay!.Value),
|
||||||
|
TimeSpan.FromMilliseconds(maxDelay!.Value),
|
||||||
if (path.Any(char.IsWhiteSpace))
|
minChunk!.Value,
|
||||||
{
|
maxChunk!.Value,
|
||||||
return "darf keine Leerzeichen enthalten.";
|
hold!.Value),
|
||||||
}
|
errors);
|
||||||
|
|
||||||
var star = path.IndexOf('*');
|
|
||||||
return star >= 0 && star != path.Length - 1 ? "* ist nur am Ende erlaubt." : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string? ValidateHost(string host)
|
|
||||||
{
|
|
||||||
if (host.Length > MaxHostLength)
|
|
||||||
{
|
|
||||||
return $"höchstens {MaxHostLength} Zeichen.";
|
|
||||||
}
|
|
||||||
|
|
||||||
return HostPattern().IsMatch(host) ? null : "ungültiger Hostname (nur Name, ohne Schema, Port oder Pfad; Wildcard als *.beispiel.de).";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static TimeSpan? ParseTimeSpan(
|
private static TimeSpan? ParseTimeSpan(
|
||||||
|
|||||||
@@ -5,19 +5,20 @@ public static class SettingKeys
|
|||||||
public const string MaxConnections = "Flypaper:MaxConnections";
|
public const string MaxConnections = "Flypaper:MaxConnections";
|
||||||
public const string MaxConnectionsPerIp = "Flypaper:MaxConnectionsPerIp";
|
public const string MaxConnectionsPerIp = "Flypaper:MaxConnectionsPerIp";
|
||||||
public const string MaxHoldDuration = "Flypaper:MaxHoldDuration";
|
public const string MaxHoldDuration = "Flypaper:MaxHoldDuration";
|
||||||
public const string TrapPaths = "Flypaper:Http:TrapPathsOverride";
|
|
||||||
public const string ExtraKnownHosts = "Flypaper:Http:ExtraKnownHosts";
|
|
||||||
public const string IgnorePrivateNetworks = "Flypaper:IgnorePrivateNetworks";
|
public const string IgnorePrivateNetworks = "Flypaper:IgnorePrivateNetworks";
|
||||||
public const string RetentionDays = "Flypaper:Retention:Days";
|
public const string RetentionDays = "Flypaper:Retention:Days";
|
||||||
|
public const string DripContent = "Flypaper:Drip:Content";
|
||||||
|
public const string DripMinDelay = "Flypaper:Drip:MinDelay";
|
||||||
|
public const string DripMaxDelay = "Flypaper:Drip:MaxDelay";
|
||||||
|
public const string DripMinChunkSize = "Flypaper:Drip:MinChunkSize";
|
||||||
|
public const string DripMaxChunkSize = "Flypaper:Drip:MaxChunkSize";
|
||||||
|
|
||||||
public static readonly IReadOnlySet<string> All = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
|
public static readonly IReadOnlyList<string> General =
|
||||||
{
|
[MaxConnections, MaxConnectionsPerIp, IgnorePrivateNetworks, RetentionDays];
|
||||||
MaxConnections,
|
|
||||||
MaxConnectionsPerIp,
|
public static readonly IReadOnlyList<string> HoldMethod =
|
||||||
MaxHoldDuration,
|
[DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, MaxHoldDuration];
|
||||||
TrapPaths,
|
|
||||||
ExtraKnownHosts,
|
public static readonly IReadOnlySet<string> All =
|
||||||
IgnorePrivateNetworks,
|
new HashSet<string>(General.Concat(HoldMethod), StringComparer.OrdinalIgnoreCase);
|
||||||
RetentionDays
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
namespace Flypaper.Core.Settings;
|
|
||||||
|
|
||||||
public static class SettingsList
|
|
||||||
{
|
|
||||||
private static readonly char[] Separators = ['\r', '\n'];
|
|
||||||
|
|
||||||
public static string[] Split(string? value) =>
|
|
||||||
value is null
|
|
||||||
? []
|
|
||||||
: value.Split(Separators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
|
||||||
.Distinct(StringComparer.Ordinal)
|
|
||||||
.ToArray();
|
|
||||||
|
|
||||||
public static string Join(IEnumerable<string> items) => string.Join('\n', items);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace Flypaper.Core.Strategies;
|
||||||
|
|
||||||
|
public enum DripContent
|
||||||
|
{
|
||||||
|
Html,
|
||||||
|
Text,
|
||||||
|
Alternating
|
||||||
|
}
|
||||||
@@ -4,6 +4,8 @@ public sealed class DripOptions
|
|||||||
{
|
{
|
||||||
public const string SectionName = "Flypaper:Drip";
|
public const string SectionName = "Flypaper:Drip";
|
||||||
|
|
||||||
|
public DripContent Content { get; set; } = DripContent.Html;
|
||||||
|
|
||||||
public TimeSpan MinDelay { get; set; } = TimeSpan.FromMilliseconds(50);
|
public TimeSpan MinDelay { get; set; } = TimeSpan.FromMilliseconds(50);
|
||||||
|
|
||||||
public TimeSpan MaxDelay { get; set; } = TimeSpan.FromSeconds(1);
|
public TimeSpan MaxDelay { get; set; } = TimeSpan.FromSeconds(1);
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Flypaper.Core.Abstractions;
|
||||||
|
using Flypaper.Core.Models;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Strategies;
|
||||||
|
|
||||||
|
public abstract class DripStrategy(
|
||||||
|
IOptionsMonitor<DripOptions> options,
|
||||||
|
IRandomSource random,
|
||||||
|
TimeProvider timeProvider) : ITarpitStrategy, IStrategyDetails
|
||||||
|
{
|
||||||
|
public abstract string Name { get; }
|
||||||
|
|
||||||
|
public abstract string MediaType { get; }
|
||||||
|
|
||||||
|
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
|
||||||
|
|
||||||
|
public string Describe()
|
||||||
|
{
|
||||||
|
var current = options.CurrentValue;
|
||||||
|
return string.Create(
|
||||||
|
CultureInfo.InvariantCulture,
|
||||||
|
$"{Name} {current.MinDelay.TotalMilliseconds:0}-{current.MaxDelay.TotalMilliseconds:0}ms {current.MinChunkSize}-{current.MaxChunkSize}B");
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task RunAsync(ITrapChannel channel, CancellationToken ct)
|
||||||
|
{
|
||||||
|
foreach (var step in DripSchedule.Create(Content(random), random, options.CurrentValue))
|
||||||
|
{
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
await channel.WriteAsync(step.Chunk, ct);
|
||||||
|
await Task.Delay(step.Delay, timeProvider, ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract IEnumerable<string> Content(IRandomSource random);
|
||||||
|
}
|
||||||
@@ -14,24 +14,6 @@ public static class HtmlContent
|
|||||||
a { color: #0b5cad; }
|
a { color: #0b5cad; }
|
||||||
""";
|
""";
|
||||||
|
|
||||||
private static readonly string[] Vocabulary =
|
|
||||||
[
|
|
||||||
"lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod",
|
|
||||||
"tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim", "ad", "minim",
|
|
||||||
"veniam", "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "aliquip", "ex", "ea",
|
|
||||||
"commodo", "consequat", "duis", "aute", "irure", "in", "reprehenderit", "voluptate", "velit", "esse",
|
|
||||||
"cillum", "fugiat", "nulla", "pariatur", "excepteur", "sint", "occaecat", "cupidatat", "non", "proident",
|
|
||||||
"sunt", "culpa", "qui", "officia", "deserunt", "mollit", "anim", "id", "est", "laborum", "praesent",
|
|
||||||
"luctus", "vitae", "semper", "facilisis", "integer", "nec", "odio", "mauris", "massa", "vestibulum",
|
|
||||||
"lacinia", "arcu", "eget", "nunc", "tristique", "fermentum", "pellentesque", "habitant", "morbi",
|
|
||||||
"senectus", "netus", "malesuada", "fames", "turpis", "egestas", "porttitor", "rhoncus", "dapibus",
|
|
||||||
"ornare", "sapien", "volutpat", "blandit", "aliquam", "etiam", "erat", "velit", "scelerisque",
|
|
||||||
"viverra", "orci", "sagittis", "eu", "tellus", "cras", "pulvinar", "mattis", "pharetra", "convallis",
|
|
||||||
"posuere", "morbi", "leo", "urna", "molestie", "at", "elementum", "sodales", "neque", "gravida",
|
|
||||||
"dictum", "fusce", "ultrices", "placerat", "euismod", "quam", "suspendisse", "potenti", "nullam",
|
|
||||||
"accumsan", "tincidunt", "varius", "sollicitudin", "imperdiet", "hendrerit", "bibendum", "cursus"
|
|
||||||
];
|
|
||||||
|
|
||||||
private static readonly string[] Sections =
|
private static readonly string[] Sections =
|
||||||
["docs", "blog", "wiki", "support", "products", "archive", "news", "help", "files", "guides", "kb", "releases"];
|
["docs", "blog", "wiki", "support", "products", "archive", "news", "help", "files", "guides", "kb", "releases"];
|
||||||
|
|
||||||
@@ -78,7 +60,7 @@ public static class HtmlContent
|
|||||||
var count = random.Next(3, 7);
|
var count = random.Next(3, 7);
|
||||||
for (var i = 0; i < count; i++)
|
for (var i = 0; i < count; i++)
|
||||||
{
|
{
|
||||||
builder.Append($"<a href=\"/{Pick(random, Sections)}/\">{Capitalize(Pick(random, Vocabulary))}</a>\n");
|
builder.Append($"<a href=\"/{Pick(random, Sections)}/\">{LoremText.Capitalize(LoremText.Word(random))}</a>\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
return builder.Append("</nav>\n").ToString();
|
return builder.Append("</nav>\n").ToString();
|
||||||
@@ -145,8 +127,8 @@ public static class HtmlContent
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
var word = Pick(random, Vocabulary);
|
var word = LoremText.Word(random);
|
||||||
builder.Append(i == 0 ? Capitalize(word) : word);
|
builder.Append(i == 0 ? LoremText.Capitalize(word) : word);
|
||||||
}
|
}
|
||||||
|
|
||||||
return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString();
|
return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString();
|
||||||
@@ -154,17 +136,13 @@ public static class HtmlContent
|
|||||||
|
|
||||||
private static string Link(IRandomSource random, int words)
|
private static string Link(IRandomSource random, int words)
|
||||||
{
|
{
|
||||||
var text = Phrase(random, words);
|
var text = LoremText.Phrase(random, words);
|
||||||
var slug = text.Replace(' ', '-');
|
var slug = text.Replace(' ', '-');
|
||||||
return $"<a href=\"/{Pick(random, Sections)}/{slug}\">{text}</a>";
|
return $"<a href=\"/{Pick(random, Sections)}/{slug}\">{text}</a>";
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string Title(IRandomSource random, int min, int max) => Capitalize(Phrase(random, random.Next(min, max + 1)));
|
private static string Title(IRandomSource random, int min, int max) => LoremText.Capitalize(LoremText.Phrase(random, random.Next(min, max + 1)));
|
||||||
|
|
||||||
private static string Phrase(IRandomSource random, int count) =>
|
|
||||||
string.Join(' ', Enumerable.Range(0, count).Select(_ => Pick(random, Vocabulary)));
|
|
||||||
|
|
||||||
private static string Pick(IRandomSource random, string[] values) => values[random.Next(0, values.Length)];
|
private static string Pick(IRandomSource random, string[] values) => values[random.Next(0, values.Length)];
|
||||||
|
|
||||||
private static string Capitalize(string value) => value.Length == 0 ? value : char.ToUpperInvariant(value[0]) + value[1..];
|
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
using Flypaper.Core.Abstractions;
|
using Flypaper.Core.Abstractions;
|
||||||
using Flypaper.Core.Models;
|
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
namespace Flypaper.Core.Strategies;
|
namespace Flypaper.Core.Strategies;
|
||||||
@@ -7,19 +6,13 @@ namespace Flypaper.Core.Strategies;
|
|||||||
public sealed class HtmlDripStrategy(
|
public sealed class HtmlDripStrategy(
|
||||||
IOptionsMonitor<DripOptions> options,
|
IOptionsMonitor<DripOptions> options,
|
||||||
IRandomSource random,
|
IRandomSource random,
|
||||||
TimeProvider timeProvider) : ITarpitStrategy
|
TimeProvider timeProvider) : DripStrategy(options, random, timeProvider)
|
||||||
{
|
{
|
||||||
public string Name => "html-drip";
|
public const string StrategyName = "html-drip";
|
||||||
|
|
||||||
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
|
public override string Name => StrategyName;
|
||||||
|
|
||||||
public async Task RunAsync(ITrapChannel channel, CancellationToken ct)
|
public override string MediaType => "text/html; charset=utf-8";
|
||||||
{
|
|
||||||
foreach (var step in DripSchedule.Create(HtmlContent.Generate(random), random, options.CurrentValue))
|
protected override IEnumerable<string> Content(IRandomSource random) => HtmlContent.Generate(random);
|
||||||
{
|
|
||||||
ct.ThrowIfCancellationRequested();
|
|
||||||
await channel.WriteAsync(step.Chunk, ct);
|
|
||||||
await Task.Delay(step.Delay, timeProvider, ct);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
using System.Text;
|
||||||
|
using Flypaper.Core.Abstractions;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Strategies;
|
||||||
|
|
||||||
|
internal static class LoremText
|
||||||
|
{
|
||||||
|
private static readonly string[] Vocabulary =
|
||||||
|
[
|
||||||
|
"lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod",
|
||||||
|
"tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim", "ad", "minim",
|
||||||
|
"veniam", "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "aliquip", "ex", "ea",
|
||||||
|
"commodo", "consequat", "duis", "aute", "irure", "in", "reprehenderit", "voluptate", "velit", "esse",
|
||||||
|
"cillum", "fugiat", "nulla", "pariatur", "excepteur", "sint", "occaecat", "cupidatat", "non", "proident",
|
||||||
|
"sunt", "culpa", "qui", "officia", "deserunt", "mollit", "anim", "id", "est", "laborum", "praesent",
|
||||||
|
"luctus", "vitae", "semper", "facilisis", "integer", "nec", "odio", "mauris", "massa", "vestibulum",
|
||||||
|
"lacinia", "arcu", "eget", "nunc", "tristique", "fermentum", "pellentesque", "habitant", "morbi",
|
||||||
|
"senectus", "netus", "malesuada", "fames", "turpis", "egestas", "porttitor", "rhoncus", "dapibus",
|
||||||
|
"ornare", "sapien", "volutpat", "blandit", "aliquam", "etiam", "erat", "velit", "scelerisque",
|
||||||
|
"viverra", "orci", "sagittis", "eu", "tellus", "cras", "pulvinar", "mattis", "pharetra", "convallis",
|
||||||
|
"posuere", "morbi", "leo", "urna", "molestie", "at", "elementum", "sodales", "neque", "gravida",
|
||||||
|
"dictum", "fusce", "ultrices", "placerat", "euismod", "quam", "suspendisse", "potenti", "nullam",
|
||||||
|
"accumsan", "tincidunt", "varius", "sollicitudin", "imperdiet", "hendrerit", "bibendum", "cursus"
|
||||||
|
];
|
||||||
|
|
||||||
|
public static string Word(IRandomSource random) => Vocabulary[random.Next(0, Vocabulary.Length)];
|
||||||
|
|
||||||
|
public static string Phrase(IRandomSource random, int count) =>
|
||||||
|
string.Join(' ', Enumerable.Range(0, count).Select(_ => Word(random)));
|
||||||
|
|
||||||
|
public static string Sentence(IRandomSource random)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
var words = random.Next(4, 21);
|
||||||
|
for (var i = 0; i < words; i++)
|
||||||
|
{
|
||||||
|
if (i > 0)
|
||||||
|
{
|
||||||
|
builder.Append(i > 2 && random.Next(0, 9) == 0 ? ", " : " ");
|
||||||
|
}
|
||||||
|
|
||||||
|
var word = Word(random);
|
||||||
|
builder.Append(i == 0 ? Capitalize(word) : word);
|
||||||
|
}
|
||||||
|
|
||||||
|
return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string Capitalize(string value) => value.Length == 0 ? value : char.ToUpperInvariant(value[0]) + value[1..];
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
using System.Text;
|
||||||
|
using Flypaper.Core.Abstractions;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Strategies;
|
||||||
|
|
||||||
|
public static class TextContent
|
||||||
|
{
|
||||||
|
public static IEnumerable<string> Generate(IRandomSource random)
|
||||||
|
{
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var builder = new StringBuilder();
|
||||||
|
var sentences = random.Next(1, 7);
|
||||||
|
for (var i = 0; i < sentences; i++)
|
||||||
|
{
|
||||||
|
if (i > 0)
|
||||||
|
{
|
||||||
|
builder.Append(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
builder.Append(LoremText.Sentence(random));
|
||||||
|
}
|
||||||
|
|
||||||
|
yield return builder.Append(random.Next(0, 4) == 0 ? "\n\n" : "\n").ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
using Flypaper.Core.Abstractions;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Strategies;
|
||||||
|
|
||||||
|
public sealed class TextDripStrategy(
|
||||||
|
IOptionsMonitor<DripOptions> options,
|
||||||
|
IRandomSource random,
|
||||||
|
TimeProvider timeProvider) : DripStrategy(options, random, timeProvider)
|
||||||
|
{
|
||||||
|
public const string StrategyName = "text-drip";
|
||||||
|
|
||||||
|
public override string Name => StrategyName;
|
||||||
|
|
||||||
|
public override string MediaType => "text/plain; charset=utf-8";
|
||||||
|
|
||||||
|
protected override IEnumerable<string> Content(IRandomSource random) => TextContent.Generate(random);
|
||||||
|
}
|
||||||
@@ -1,39 +1,40 @@
|
|||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Net.Sockets;
|
using System.Net.Sockets;
|
||||||
using Flypaper.Core.Settings;
|
|
||||||
using Flypaper.Http.Matching;
|
|
||||||
using Flypaper.Http.Middleware;
|
using Flypaper.Http.Middleware;
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.AspNetCore.HttpOverrides;
|
using Microsoft.AspNetCore.HttpOverrides;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
namespace Flypaper.Http;
|
namespace Flypaper.Http;
|
||||||
|
|
||||||
public static class FlypaperHttpExtensions
|
public static class FlypaperHttpExtensions
|
||||||
{
|
{
|
||||||
|
private static readonly string[] DefaultTrustedProxies = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"];
|
||||||
|
|
||||||
|
private static readonly string[] RemovedSettings =
|
||||||
|
[
|
||||||
|
"Flypaper:Http:KnownHosts",
|
||||||
|
"Flypaper:Http:TrapPaths",
|
||||||
|
"Flypaper:Http:ExtraKnownHosts",
|
||||||
|
"Flypaper:Http:TrapPathsOverride"
|
||||||
|
];
|
||||||
|
|
||||||
public static IServiceCollection AddFlypaperHttp(this IServiceCollection services, IConfiguration configuration)
|
public static IServiceCollection AddFlypaperHttp(this IServiceCollection services, IConfiguration configuration)
|
||||||
{
|
{
|
||||||
services.Configure<HttpTrapOptions>(configuration.GetSection(HttpTrapOptions.SectionName));
|
services.Configure<HttpTrapOptions>(configuration.GetSection(HttpTrapOptions.SectionName));
|
||||||
services.PostConfigure<HttpTrapOptions>(options =>
|
services.Configure<PortOptions>(configuration.GetSection(PortOptions.SectionName));
|
||||||
{
|
|
||||||
if (options.TrapPathsOverride is not null)
|
|
||||||
{
|
|
||||||
options.TrapPaths = SettingsList.Split(options.TrapPathsOverride);
|
|
||||||
}
|
|
||||||
|
|
||||||
options.KnownHosts = options.KnownHosts.Concat(SettingsList.Split(options.ExtraKnownHosts)).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
|
|
||||||
});
|
|
||||||
services.TryAddSingleton<TrapMatcher>();
|
|
||||||
|
|
||||||
services.AddOptions<ForwardedHeadersOptions>()
|
services.AddOptions<ForwardedHeadersOptions>()
|
||||||
.Configure<IOptions<HttpTrapOptions>>((forwarded, trap) =>
|
.Configure<IOptions<HttpTrapOptions>>((forwarded, trap) =>
|
||||||
{
|
{
|
||||||
forwarded.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
forwarded.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
|
||||||
forwarded.ForwardLimit = 1;
|
forwarded.ForwardLimit = 1;
|
||||||
foreach (var proxy in trap.Value.TrustedProxies)
|
var configured = trap.Value.TrustedProxies.Where(proxy => !string.IsNullOrWhiteSpace(proxy)).ToArray();
|
||||||
|
var proxies = configured.Length > 0 ? configured : DefaultTrustedProxies;
|
||||||
|
foreach (var proxy in proxies)
|
||||||
{
|
{
|
||||||
forwarded.KnownIPNetworks.Add(System.Net.IPNetwork.Parse(proxy.Contains('/') ? proxy : $"{proxy}/{HostBits(proxy)}"));
|
forwarded.KnownIPNetworks.Add(System.Net.IPNetwork.Parse(proxy.Contains('/') ? proxy : $"{proxy}/{HostBits(proxy)}"));
|
||||||
}
|
}
|
||||||
@@ -50,6 +51,16 @@ public static class FlypaperHttpExtensions
|
|||||||
return app;
|
return app;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static void WarnAboutRemovedSettings(IConfiguration configuration, ILogger logger)
|
||||||
|
{
|
||||||
|
foreach (var key in RemovedSettings.Where(key => configuration.GetSection(key).Exists()))
|
||||||
|
{
|
||||||
|
logger.LogWarning(
|
||||||
|
"Setting {Key} is set but no longer has any effect: every request on the trap port is caught",
|
||||||
|
key.Replace(":", "__", StringComparison.Ordinal));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static int HostBits(string address) =>
|
private static int HostBits(string address) =>
|
||||||
IPAddress.Parse(address).AddressFamily == AddressFamily.InterNetworkV6 ? 128 : 32;
|
IPAddress.Parse(address).AddressFamily == AddressFamily.InterNetworkV6 ? 128 : 32;
|
||||||
}
|
}
|
||||||
@@ -6,13 +6,5 @@ public sealed class HttpTrapOptions
|
|||||||
|
|
||||||
public const string HealthPath = "/health";
|
public const string HealthPath = "/health";
|
||||||
|
|
||||||
public string[] KnownHosts { get; set; } = [];
|
|
||||||
|
|
||||||
public string[] TrapPaths { get; set; } = [];
|
|
||||||
|
|
||||||
public string[] TrustedProxies { get; set; } = [];
|
public string[] TrustedProxies { get; set; } = [];
|
||||||
|
|
||||||
public string? TrapPathsOverride { get; set; }
|
|
||||||
|
|
||||||
public string? ExtraKnownHosts { get; set; }
|
|
||||||
}
|
}
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
namespace Flypaper.Http.Matching;
|
|
||||||
|
|
||||||
public enum TrapMatch
|
|
||||||
{
|
|
||||||
None,
|
|
||||||
UnknownHost,
|
|
||||||
TrapPath
|
|
||||||
}
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
using Microsoft.Extensions.Options;
|
|
||||||
|
|
||||||
namespace Flypaper.Http.Matching;
|
|
||||||
|
|
||||||
public sealed class TrapMatcher : IDisposable
|
|
||||||
{
|
|
||||||
private readonly IDisposable? _subscription;
|
|
||||||
private volatile Snapshot _snapshot;
|
|
||||||
|
|
||||||
public TrapMatcher(IOptionsMonitor<HttpTrapOptions> options)
|
|
||||||
{
|
|
||||||
_snapshot = new Snapshot(options.CurrentValue);
|
|
||||||
_subscription = options.OnChange(updated => _snapshot = new Snapshot(updated));
|
|
||||||
}
|
|
||||||
|
|
||||||
public TrapMatch Match(string? host, string? path)
|
|
||||||
{
|
|
||||||
var snapshot = _snapshot;
|
|
||||||
if (!snapshot.IsKnownHost(host))
|
|
||||||
{
|
|
||||||
return TrapMatch.UnknownHost;
|
|
||||||
}
|
|
||||||
|
|
||||||
return snapshot.IsTrapPath(path ?? "/") ? TrapMatch.TrapPath : TrapMatch.None;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose() => _subscription?.Dispose();
|
|
||||||
|
|
||||||
private sealed class Snapshot
|
|
||||||
{
|
|
||||||
private readonly HashSet<string> _hosts = new(StringComparer.OrdinalIgnoreCase);
|
|
||||||
private readonly List<string> _hostSuffixes = [];
|
|
||||||
private readonly HashSet<string> _paths = new(StringComparer.OrdinalIgnoreCase);
|
|
||||||
private readonly List<string> _pathPrefixes = [];
|
|
||||||
|
|
||||||
public Snapshot(HttpTrapOptions options)
|
|
||||||
{
|
|
||||||
foreach (var host in options.KnownHosts.Where(h => !string.IsNullOrWhiteSpace(h)))
|
|
||||||
{
|
|
||||||
if (host.StartsWith("*.", StringComparison.Ordinal))
|
|
||||||
{
|
|
||||||
_hostSuffixes.Add(host[1..]);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_hosts.Add(host);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (var path in options.TrapPaths.Where(p => !string.IsNullOrWhiteSpace(p)))
|
|
||||||
{
|
|
||||||
if (path.EndsWith('*'))
|
|
||||||
{
|
|
||||||
_pathPrefixes.Add(path[..^1]);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_paths.Add(TrimTrailingSlash(path));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool IsKnownHost(string? host) =>
|
|
||||||
!string.IsNullOrEmpty(host)
|
|
||||||
&& (_hosts.Contains(host)
|
|
||||||
|| _hostSuffixes.Any(suffix => host.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)));
|
|
||||||
|
|
||||||
public bool IsTrapPath(string path) =>
|
|
||||||
_paths.Contains(TrimTrailingSlash(path))
|
|
||||||
|| _pathPrefixes.Any(prefix => path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
|
|
||||||
|
|
||||||
private static string TrimTrailingSlash(string path) => path.Length > 1 ? path.TrimEnd('/') : path;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,28 +3,29 @@ using Flypaper.Core.Abstractions;
|
|||||||
using Flypaper.Core.Models;
|
using Flypaper.Core.Models;
|
||||||
using Flypaper.Core.Networking;
|
using Flypaper.Core.Networking;
|
||||||
using Flypaper.Core.Runtime;
|
using Flypaper.Core.Runtime;
|
||||||
using Flypaper.Http.Matching;
|
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Http.Features;
|
using Microsoft.AspNetCore.Http.Features;
|
||||||
using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
|
using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
namespace Flypaper.Http.Middleware;
|
namespace Flypaper.Http.Middleware;
|
||||||
|
|
||||||
internal sealed class FlypaperMiddleware(
|
internal sealed class FlypaperMiddleware(
|
||||||
RequestDelegate next,
|
RequestDelegate next,
|
||||||
TrapMatcher matcher,
|
|
||||||
TrapRunner runner,
|
TrapRunner runner,
|
||||||
|
IOptions<PortOptions> ports,
|
||||||
TimeProvider timeProvider)
|
TimeProvider timeProvider)
|
||||||
{
|
{
|
||||||
public async Task InvokeAsync(HttpContext context)
|
public async Task InvokeAsync(HttpContext context)
|
||||||
{
|
{
|
||||||
var request = context.Request;
|
if (context.Connection.LocalPort == ports.Value.Dashboard || IsInternalHealthProbe(context))
|
||||||
if (IsInternalHealthProbe(context) || matcher.Match(request.Host.Host, request.Path.Value) == TrapMatch.None)
|
|
||||||
{
|
{
|
||||||
await next(context);
|
await next(context);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var request = context.Request;
|
||||||
|
|
||||||
var session = new TrapSession(
|
var session = new TrapSession(
|
||||||
Guid.NewGuid(),
|
Guid.NewGuid(),
|
||||||
TrapProtocol.Http,
|
TrapProtocol.Http,
|
||||||
@@ -33,12 +34,12 @@ internal sealed class FlypaperMiddleware(
|
|||||||
|
|
||||||
var trapContext = new TrapContext(
|
var trapContext = new TrapContext(
|
||||||
session,
|
session,
|
||||||
$"{request.Method} {request.Host}{request.Path}{request.QueryString}",
|
$"{request.Method} {StoredHost(request.Host)}{request.Path}{request.QueryString}",
|
||||||
request.Headers.UserAgent.ToString());
|
request.Headers.UserAgent.ToString());
|
||||||
|
|
||||||
var outcome = await runner.RunAsync(
|
var outcome = await runner.RunAsync(
|
||||||
trapContext,
|
trapContext,
|
||||||
ct => OpenChannelAsync(context, session, ct),
|
(strategy, ct) => OpenChannelAsync(context, session, strategy, ct),
|
||||||
context.RequestAborted);
|
context.RequestAborted);
|
||||||
|
|
||||||
if (outcome == TrapOutcome.Rejected && !context.Response.HasStarted)
|
if (outcome == TrapOutcome.Rejected && !context.Response.HasStarted)
|
||||||
@@ -47,6 +48,9 @@ internal sealed class FlypaperMiddleware(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static string StoredHost(HostString host) =>
|
||||||
|
string.IsNullOrEmpty(host.Host) || host.Host == "_" ? "" : host.Value!;
|
||||||
|
|
||||||
private static bool IsInternalHealthProbe(HttpContext context) =>
|
private static bool IsInternalHealthProbe(HttpContext context) =>
|
||||||
context.Request.Path.Equals(HttpTrapOptions.HealthPath, StringComparison.OrdinalIgnoreCase)
|
context.Request.Path.Equals(HttpTrapOptions.HealthPath, StringComparison.OrdinalIgnoreCase)
|
||||||
&& context.Connection.RemoteIpAddress is { } remoteIp
|
&& context.Connection.RemoteIpAddress is { } remoteIp
|
||||||
@@ -55,6 +59,7 @@ internal sealed class FlypaperMiddleware(
|
|||||||
private static async ValueTask<ITrapChannel> OpenChannelAsync(
|
private static async ValueTask<ITrapChannel> OpenChannelAsync(
|
||||||
HttpContext context,
|
HttpContext context,
|
||||||
TrapSession session,
|
TrapSession session,
|
||||||
|
ITarpitStrategy strategy,
|
||||||
CancellationToken ct)
|
CancellationToken ct)
|
||||||
{
|
{
|
||||||
var minDataRate = context.Features.Get<IHttpMinResponseDataRateFeature>();
|
var minDataRate = context.Features.Get<IHttpMinResponseDataRateFeature>();
|
||||||
@@ -67,7 +72,7 @@ internal sealed class FlypaperMiddleware(
|
|||||||
|
|
||||||
var response = context.Response;
|
var response = context.Response;
|
||||||
response.StatusCode = StatusCodes.Status200OK;
|
response.StatusCode = StatusCodes.Status200OK;
|
||||||
response.ContentType = "text/html; charset=utf-8";
|
response.ContentType = strategy is IStrategyDetails details ? details.MediaType : "text/html; charset=utf-8";
|
||||||
response.Headers.CacheControl = "no-store";
|
response.Headers.CacheControl = "no-store";
|
||||||
response.Headers["X-Accel-Buffering"] = "no";
|
response.Headers["X-Accel-Buffering"] = "no";
|
||||||
await response.StartAsync(ct);
|
await response.StartAsync(ct);
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
namespace Flypaper.Http;
|
||||||
|
|
||||||
|
public sealed class PortOptions
|
||||||
|
{
|
||||||
|
public const string SectionName = "Flypaper:Ports";
|
||||||
|
|
||||||
|
public int Trap { get; set; } = 8080;
|
||||||
|
|
||||||
|
public int Dashboard { get; set; } = 8081;
|
||||||
|
}
|
||||||
@@ -1,14 +1,13 @@
|
|||||||
using Flypaper.Storage.Entities;
|
|
||||||
|
|
||||||
namespace Flypaper.Storage.Dashboard;
|
namespace Flypaper.Storage.Dashboard;
|
||||||
|
|
||||||
public sealed record DashboardData(
|
public sealed record DashboardData(
|
||||||
int TotalCatches,
|
int TotalCatches,
|
||||||
int CatchesLast24Hours,
|
int CatchesLast24Hours,
|
||||||
int Rejected,
|
int Rejected,
|
||||||
|
int RejectedLast24Hours,
|
||||||
int UniqueIps,
|
int UniqueIps,
|
||||||
|
int UniqueIpsLast24Hours,
|
||||||
TimeSpan TotalHoldTime,
|
TimeSpan TotalHoldTime,
|
||||||
IReadOnlyList<TrapEventEntity> Recent,
|
|
||||||
IReadOnlyList<TopEntry> TopIps,
|
IReadOnlyList<TopEntry> TopIps,
|
||||||
IReadOnlyList<TopEntry> TopTargets,
|
IReadOnlyList<TopEntry> TopTargets,
|
||||||
IReadOnlyList<TopEntry> TopCountries,
|
IReadOnlyList<TopEntry> TopCountries,
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ namespace Flypaper.Storage.Dashboard;
|
|||||||
|
|
||||||
public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
|
public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
|
||||||
{
|
{
|
||||||
private const int RecentCount = 50;
|
|
||||||
private const int TopCount = 10;
|
private const int TopCount = 10;
|
||||||
|
|
||||||
public async Task<DashboardData> GetAsync(CancellationToken ct = default)
|
public async Task<DashboardData> GetAsync(CancellationToken ct = default)
|
||||||
@@ -37,9 +36,10 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
|
|||||||
await catches.CountAsync(ct),
|
await catches.CountAsync(ct),
|
||||||
await catches.CountAsync(e => e.StartedAt >= since, ct),
|
await catches.CountAsync(e => e.StartedAt >= since, ct),
|
||||||
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct),
|
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct),
|
||||||
|
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected && e.StartedAt >= since, ct),
|
||||||
await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct),
|
await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct),
|
||||||
|
await events.Where(e => e.StartedAt >= since).Select(e => e.RemoteIp).Distinct().CountAsync(ct),
|
||||||
TimeSpan.FromMilliseconds(await catches.SumAsync(e => e.DurationMs, ct)),
|
TimeSpan.FromMilliseconds(await catches.SumAsync(e => e.DurationMs, ct)),
|
||||||
await events.OrderByDescending(e => e.Id).Take(RecentCount).ToListAsync(ct),
|
|
||||||
await TopAsync(catches.GroupBy(e => e.RemoteIp), ct),
|
await TopAsync(catches.GroupBy(e => e.RemoteIp), ct),
|
||||||
await TopAsync(catches.Where(e => e.Target != null).GroupBy(e => e.Target!), ct),
|
await TopAsync(catches.Where(e => e.Target != null).GroupBy(e => e.Target!), ct),
|
||||||
countries
|
countries
|
||||||
@@ -52,6 +52,71 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
|
|||||||
countries.ToDictionary(x => x.Key, x => x.Count, StringComparer.OrdinalIgnoreCase));
|
countries.ToDictionary(x => x.Key, x => x.Count, StringComparer.OrdinalIgnoreCase));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<RecentCatches> GetRecentAsync(RecentFilter filter, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
var events = Apply(db.TrapEvents.AsNoTracking(), filter);
|
||||||
|
|
||||||
|
var countries = await db.TrapEvents
|
||||||
|
.Where(e => e.CountryCode != null)
|
||||||
|
.GroupBy(e => e.CountryCode!)
|
||||||
|
.Select(g => new CountryOption(g.Key, g.Max(e => e.Country)))
|
||||||
|
.ToListAsync(ct);
|
||||||
|
|
||||||
|
return new RecentCatches(
|
||||||
|
await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id)
|
||||||
|
.Take(Math.Clamp(filter.Limit, 1, RecentFilter.MaxLimit))
|
||||||
|
.ToListAsync(ct),
|
||||||
|
await events.CountAsync(ct),
|
||||||
|
countries);
|
||||||
|
}
|
||||||
|
|
||||||
|
private IQueryable<TrapEventEntity> Apply(IQueryable<TrapEventEntity> events, RecentFilter filter)
|
||||||
|
{
|
||||||
|
if (filter.Window is { } window)
|
||||||
|
{
|
||||||
|
var since = timeProvider.GetUtcNow().UtcDateTime - window;
|
||||||
|
events = events.Where(e => e.StartedAt >= since);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (filter.Outcome is { } outcome)
|
||||||
|
{
|
||||||
|
events = events.Where(e => e.Outcome == outcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (filter.CountryCode is { } country)
|
||||||
|
{
|
||||||
|
events = events.Where(e => e.CountryCode == country);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (filter.Asn is { } asn)
|
||||||
|
{
|
||||||
|
events = events.Where(e => e.Asn == asn);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (filter.Ip is { } ip)
|
||||||
|
{
|
||||||
|
events = events.Where(e => e.RemoteIp == ip);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (filter.Target is { } target)
|
||||||
|
{
|
||||||
|
events = events.Where(e => e.Target == target);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(filter.Search))
|
||||||
|
{
|
||||||
|
var pattern = $"%{filter.Search.Trim().Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_")}%";
|
||||||
|
events = events.Where(e =>
|
||||||
|
EF.Functions.Like(e.RemoteIp, pattern, "\\")
|
||||||
|
|| EF.Functions.Like(e.Provider!, pattern, "\\")
|
||||||
|
|| EF.Functions.Like(e.Target!, pattern, "\\")
|
||||||
|
|| EF.Functions.Like(e.ClientInfo!, pattern, "\\"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return events;
|
||||||
|
}
|
||||||
|
|
||||||
private static async Task<IReadOnlyList<TopEntry>> TopAsync(
|
private static async Task<IReadOnlyList<TopEntry>> TopAsync(
|
||||||
IQueryable<IGrouping<string, TrapEventEntity>> groups,
|
IQueryable<IGrouping<string, TrapEventEntity>> groups,
|
||||||
CancellationToken ct)
|
CancellationToken ct)
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using Flypaper.Core.Models;
|
||||||
|
using Flypaper.Storage.Entities;
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Dashboard;
|
||||||
|
|
||||||
|
public sealed record RecentFilter(
|
||||||
|
TimeSpan? Window = null,
|
||||||
|
TrapOutcome? Outcome = null,
|
||||||
|
string? CountryCode = null,
|
||||||
|
long? Asn = null,
|
||||||
|
string? Ip = null,
|
||||||
|
string? Target = null,
|
||||||
|
string? Search = null,
|
||||||
|
int Limit = RecentFilter.DefaultLimit)
|
||||||
|
{
|
||||||
|
public const int DefaultLimit = 50;
|
||||||
|
public const int MaxLimit = 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record RecentCatches(IReadOnlyList<TrapEventEntity> Items, int Total, IReadOnlyList<CountryOption> Countries);
|
||||||
|
|
||||||
|
public sealed record CountryOption(string Code, string? Name);
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
namespace Flypaper.Storage.Entities;
|
||||||
|
|
||||||
|
public sealed class McpTokenEntity
|
||||||
|
{
|
||||||
|
public int Id { get; set; }
|
||||||
|
|
||||||
|
public required string Name { get; set; }
|
||||||
|
|
||||||
|
public required string TokenHash { get; set; }
|
||||||
|
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
|
public DateTime? LastUsedAt { get; set; }
|
||||||
|
}
|
||||||
@@ -12,6 +12,8 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
|
|||||||
|
|
||||||
public DbSet<SettingEntity> Settings => Set<SettingEntity>();
|
public DbSet<SettingEntity> Settings => Set<SettingEntity>();
|
||||||
|
|
||||||
|
public DbSet<McpTokenEntity> McpTokens => Set<McpTokenEntity>();
|
||||||
|
|
||||||
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) =>
|
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) =>
|
||||||
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
|
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
|
||||||
|
|
||||||
@@ -36,5 +38,10 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
|
|||||||
var setting = modelBuilder.Entity<SettingEntity>();
|
var setting = modelBuilder.Entity<SettingEntity>();
|
||||||
setting.HasKey(e => e.Key);
|
setting.HasKey(e => e.Key);
|
||||||
setting.Property(e => e.Key).HasMaxLength(128);
|
setting.Property(e => e.Key).HasMaxLength(128);
|
||||||
|
|
||||||
|
var mcpToken = modelBuilder.Entity<McpTokenEntity>();
|
||||||
|
mcpToken.Property(e => e.Name).HasMaxLength(100);
|
||||||
|
mcpToken.Property(e => e.TokenHash).HasMaxLength(64);
|
||||||
|
mcpToken.HasIndex(e => e.TokenHash).IsUnique();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@ using Flypaper.Core.Abstractions;
|
|||||||
using Flypaper.Storage.Dashboard;
|
using Flypaper.Storage.Dashboard;
|
||||||
using Flypaper.Storage.Events;
|
using Flypaper.Storage.Events;
|
||||||
using Flypaper.Storage.Maintenance;
|
using Flypaper.Storage.Maintenance;
|
||||||
|
using Flypaper.Storage.Queries;
|
||||||
using Flypaper.Storage.Settings;
|
using Flypaper.Storage.Settings;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
@@ -20,6 +21,8 @@ public static class FlypaperStorageExtensions
|
|||||||
builder.Configuration.Add(source);
|
builder.Configuration.Add(source);
|
||||||
builder.Services.AddSingleton(source);
|
builder.Services.AddSingleton(source);
|
||||||
builder.Services.AddSingleton<RuntimeSettingsStore>();
|
builder.Services.AddSingleton<RuntimeSettingsStore>();
|
||||||
|
builder.Services.AddSingleton<AdminCredentialStore>();
|
||||||
|
builder.Services.AddSingleton<McpTokenStore>();
|
||||||
builder.Services.Configure<RetentionOptions>(builder.Configuration.GetSection(RetentionOptions.SectionName));
|
builder.Services.Configure<RetentionOptions>(builder.Configuration.GetSection(RetentionOptions.SectionName));
|
||||||
builder.Services.AddFlypaperStorage(connectionString);
|
builder.Services.AddFlypaperStorage(connectionString);
|
||||||
|
|
||||||
@@ -34,6 +37,7 @@ public static class FlypaperStorageExtensions
|
|||||||
services.AddHostedService<TrapEventWriter>();
|
services.AddHostedService<TrapEventWriter>();
|
||||||
services.AddHostedService<OriginBackfill>();
|
services.AddHostedService<OriginBackfill>();
|
||||||
services.AddSingleton<DashboardQueries>();
|
services.AddSingleton<DashboardQueries>();
|
||||||
|
services.AddSingleton<CatchQueries>();
|
||||||
services.AddSingleton<TrapDataMaintenance>();
|
services.AddSingleton<TrapDataMaintenance>();
|
||||||
services.AddHostedService<RetentionCleanup>();
|
services.AddHostedService<RetentionCleanup>();
|
||||||
return services;
|
return services;
|
||||||
|
|||||||
+121
@@ -0,0 +1,121 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using Flypaper.Storage;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(FlypaperDbContext))]
|
||||||
|
[Migration("20261115114013_NormalizeMissingHost")]
|
||||||
|
partial class NormalizeMissingHost
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
||||||
|
|
||||||
|
modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<string>("Key")
|
||||||
|
.HasMaxLength(128)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Value")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Key");
|
||||||
|
|
||||||
|
b.ToTable("Settings");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<long?>("Asn")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<long>("BytesSent")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("City")
|
||||||
|
.HasMaxLength(256)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("ClientInfo")
|
||||||
|
.HasMaxLength(2048)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Country")
|
||||||
|
.HasMaxLength(256)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("CountryCode")
|
||||||
|
.HasMaxLength(2)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<long>("DurationMs")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<DateTime>("EndedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Outcome")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(16)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Protocol")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(16)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Provider")
|
||||||
|
.HasMaxLength(256)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("RemoteIp")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<Guid>("SessionId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTime>("StartedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Strategy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Target")
|
||||||
|
.HasMaxLength(2048)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("Asn");
|
||||||
|
|
||||||
|
b.HasIndex("CountryCode");
|
||||||
|
|
||||||
|
b.HasIndex("RemoteIp");
|
||||||
|
|
||||||
|
b.HasIndex("StartedAt");
|
||||||
|
|
||||||
|
b.ToTable("TrapEvents");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class NormalizeMissingHost : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.Sql("""
|
||||||
|
UPDATE "TrapEvents"
|
||||||
|
SET "Target" = substr("Target", 1, instr("Target", ' _/')) || substr("Target", instr("Target", ' _/') + 2)
|
||||||
|
WHERE instr("Target", ' _/') > 0;
|
||||||
|
""");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using Flypaper.Storage;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(FlypaperDbContext))]
|
||||||
|
[Migration("20261115122552_AddMcpTokens")]
|
||||||
|
partial class AddMcpTokens
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
||||||
|
|
||||||
|
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<DateTime>("CreatedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTime?>("LastUsedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(100)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("TokenHash")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("TokenHash")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.ToTable("McpTokens");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<string>("Key")
|
||||||
|
.HasMaxLength(128)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Value")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Key");
|
||||||
|
|
||||||
|
b.ToTable("Settings");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<long?>("Asn")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<long>("BytesSent")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("City")
|
||||||
|
.HasMaxLength(256)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("ClientInfo")
|
||||||
|
.HasMaxLength(2048)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Country")
|
||||||
|
.HasMaxLength(256)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("CountryCode")
|
||||||
|
.HasMaxLength(2)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<long>("DurationMs")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<DateTime>("EndedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Outcome")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(16)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Protocol")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(16)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Provider")
|
||||||
|
.HasMaxLength(256)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("RemoteIp")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<Guid>("SessionId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTime>("StartedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Strategy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Target")
|
||||||
|
.HasMaxLength(2048)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("Asn");
|
||||||
|
|
||||||
|
b.HasIndex("CountryCode");
|
||||||
|
|
||||||
|
b.HasIndex("RemoteIp");
|
||||||
|
|
||||||
|
b.HasIndex("StartedAt");
|
||||||
|
|
||||||
|
b.ToTable("TrapEvents");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
using System;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class AddMcpTokens : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.CreateTable(
|
||||||
|
name: "McpTokens",
|
||||||
|
columns: table => new
|
||||||
|
{
|
||||||
|
Id = table.Column<int>(type: "INTEGER", nullable: false)
|
||||||
|
.Annotation("Sqlite:Autoincrement", true),
|
||||||
|
Name = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
|
||||||
|
TokenHash = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
|
||||||
|
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
|
||||||
|
LastUsedAt = table.Column<DateTime>(type: "TEXT", nullable: true)
|
||||||
|
},
|
||||||
|
constraints: table =>
|
||||||
|
{
|
||||||
|
table.PrimaryKey("PK_McpTokens", x => x.Id);
|
||||||
|
});
|
||||||
|
|
||||||
|
migrationBuilder.CreateIndex(
|
||||||
|
name: "IX_McpTokens_TokenHash",
|
||||||
|
table: "McpTokens",
|
||||||
|
column: "TokenHash",
|
||||||
|
unique: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.DropTable(
|
||||||
|
name: "McpTokens");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+151
@@ -0,0 +1,151 @@
|
|||||||
|
// <auto-generated />
|
||||||
|
using System;
|
||||||
|
using Flypaper.Storage;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Migrations
|
||||||
|
{
|
||||||
|
[DbContext(typeof(FlypaperDbContext))]
|
||||||
|
[Migration("20261115175305_RemoveTrapPathSettings")]
|
||||||
|
partial class RemoveTrapPathSettings
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
#pragma warning disable 612, 618
|
||||||
|
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
||||||
|
|
||||||
|
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<DateTime>("CreatedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTime?>("LastUsedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(100)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("TokenHash")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("TokenHash")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.ToTable("McpTokens");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<string>("Key")
|
||||||
|
.HasMaxLength(128)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Value")
|
||||||
|
.IsRequired()
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Key");
|
||||||
|
|
||||||
|
b.ToTable("Settings");
|
||||||
|
});
|
||||||
|
|
||||||
|
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<long>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<long?>("Asn")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<long>("BytesSent")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<string>("City")
|
||||||
|
.HasMaxLength(256)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("ClientInfo")
|
||||||
|
.HasMaxLength(2048)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Country")
|
||||||
|
.HasMaxLength(256)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("CountryCode")
|
||||||
|
.HasMaxLength(2)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<long>("DurationMs")
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<DateTime>("EndedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Outcome")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(16)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Protocol")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(16)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Provider")
|
||||||
|
.HasMaxLength(256)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("RemoteIp")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<Guid>("SessionId")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTime>("StartedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Strategy")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Target")
|
||||||
|
.HasMaxLength(2048)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("Asn");
|
||||||
|
|
||||||
|
b.HasIndex("CountryCode");
|
||||||
|
|
||||||
|
b.HasIndex("RemoteIp");
|
||||||
|
|
||||||
|
b.HasIndex("StartedAt");
|
||||||
|
|
||||||
|
b.ToTable("TrapEvents");
|
||||||
|
});
|
||||||
|
#pragma warning restore 612, 618
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore.Migrations;
|
||||||
|
|
||||||
|
#nullable disable
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Migrations
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
public partial class RemoveTrapPathSettings : Migration
|
||||||
|
{
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Up(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
migrationBuilder.Sql("DELETE FROM \"Settings\" WHERE \"Key\" IN ('Flypaper:Http:ExtraKnownHosts', 'Flypaper:Http:TrapPathsOverride');");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <inheritdoc />
|
||||||
|
protected override void Down(MigrationBuilder migrationBuilder)
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,6 +17,36 @@ namespace Flypaper.Storage.Migrations
|
|||||||
#pragma warning disable 612, 618
|
#pragma warning disable 612, 618
|
||||||
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
|
||||||
|
|
||||||
|
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
|
||||||
|
{
|
||||||
|
b.Property<int>("Id")
|
||||||
|
.ValueGeneratedOnAdd()
|
||||||
|
.HasColumnType("INTEGER");
|
||||||
|
|
||||||
|
b.Property<DateTime>("CreatedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<DateTime?>("LastUsedAt")
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("Name")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(100)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.Property<string>("TokenHash")
|
||||||
|
.IsRequired()
|
||||||
|
.HasMaxLength(64)
|
||||||
|
.HasColumnType("TEXT");
|
||||||
|
|
||||||
|
b.HasKey("Id");
|
||||||
|
|
||||||
|
b.HasIndex("TokenHash")
|
||||||
|
.IsUnique();
|
||||||
|
|
||||||
|
b.ToTable("McpTokens");
|
||||||
|
});
|
||||||
|
|
||||||
modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b =>
|
modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b =>
|
||||||
{
|
{
|
||||||
b.Property<string>("Key")
|
b.Property<string>("Key")
|
||||||
|
|||||||
@@ -0,0 +1,189 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Flypaper.Core.Models;
|
||||||
|
using Flypaper.Storage.Entities;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Queries;
|
||||||
|
|
||||||
|
public sealed class CatchQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory)
|
||||||
|
{
|
||||||
|
public const int MaxLimit = 500;
|
||||||
|
|
||||||
|
public async Task<CatchStats> GetStatsAsync(DateTime? since, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
var events = InPeriod(db, since);
|
||||||
|
var catches = events.Where(e => e.Outcome != TrapOutcome.Rejected);
|
||||||
|
|
||||||
|
var count = await catches.CountAsync(ct);
|
||||||
|
var totalMs = count == 0 ? 0 : await catches.SumAsync(e => e.DurationMs, ct);
|
||||||
|
var longest = await catches.OrderByDescending(e => e.DurationMs).ThenByDescending(e => e.Id).FirstOrDefaultAsync(ct);
|
||||||
|
|
||||||
|
return new CatchStats(
|
||||||
|
count,
|
||||||
|
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct),
|
||||||
|
await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct),
|
||||||
|
totalMs / 1000d,
|
||||||
|
count == 0 ? 0 : totalMs / 1000d / count,
|
||||||
|
longest is null ? null : ToRecord(longest));
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<CatchRecord>> ListAsync(CatchFilter filter, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
var events = InPeriod(db, filter.Since);
|
||||||
|
|
||||||
|
if (filter.Until is { } until)
|
||||||
|
{
|
||||||
|
events = events.Where(e => e.StartedAt < until);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(filter.Country))
|
||||||
|
{
|
||||||
|
var country = filter.Country.Trim().ToUpperInvariant();
|
||||||
|
events = events.Where(e => e.CountryCode == country);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(filter.Provider))
|
||||||
|
{
|
||||||
|
events = ByProvider(events, filter.Provider.Trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(filter.Ip))
|
||||||
|
{
|
||||||
|
var ip = filter.Ip.Trim();
|
||||||
|
events = events.Where(e => e.RemoteIp == ip);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(filter.TargetContains))
|
||||||
|
{
|
||||||
|
var text = filter.TargetContains.Trim().ToLowerInvariant();
|
||||||
|
events = events.Where(e => e.Target != null && e.Target.ToLower().Contains(text));
|
||||||
|
}
|
||||||
|
|
||||||
|
var rows = await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).Take(Clamp(filter.Limit)).ToListAsync(ct);
|
||||||
|
return rows.Select(ToRecord).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<CatchRecord>> LongestAsync(DateTime? since, int limit, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
var rows = await InPeriod(db, since)
|
||||||
|
.Where(e => e.Outcome != TrapOutcome.Rejected)
|
||||||
|
.OrderByDescending(e => e.DurationMs)
|
||||||
|
.ThenByDescending(e => e.Id)
|
||||||
|
.Take(Clamp(limit))
|
||||||
|
.ToListAsync(ct);
|
||||||
|
return rows.Select(ToRecord).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<TopItem>> TopAsync(TopDimension dimension, DateTime? since, int limit, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
var catches = InPeriod(db, since).Where(e => e.Outcome != TrapOutcome.Rejected);
|
||||||
|
var take = Clamp(limit);
|
||||||
|
|
||||||
|
IQueryable<TopRow> rows = dimension switch
|
||||||
|
{
|
||||||
|
TopDimension.Ips => catches.GroupBy(e => e.RemoteIp)
|
||||||
|
.Select(g => new TopRow { Key = g.Key, Label = g.Max(e => e.CountryCode), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
|
||||||
|
TopDimension.Countries => catches.Where(e => e.CountryCode != null).GroupBy(e => e.CountryCode!)
|
||||||
|
.Select(g => new TopRow { Key = g.Key, Label = g.Max(e => e.Country), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
|
||||||
|
TopDimension.Providers => catches.Where(e => e.Asn != null).GroupBy(e => e.Asn!.Value)
|
||||||
|
.Select(g => new TopRow { Key = "AS" + g.Key.ToString(), Label = g.Max(e => e.Provider), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
|
||||||
|
TopDimension.Targets => catches.Where(e => e.Target != null).GroupBy(e => e.Target!)
|
||||||
|
.Select(g => new TopRow { Key = g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
|
||||||
|
TopDimension.UserAgents => catches.Where(e => e.ClientInfo != null).GroupBy(e => e.ClientInfo!)
|
||||||
|
.Select(g => new TopRow { Key = g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
|
||||||
|
_ => throw new ArgumentOutOfRangeException(nameof(dimension))
|
||||||
|
};
|
||||||
|
|
||||||
|
var top = await rows
|
||||||
|
.OrderByDescending(x => x.Count)
|
||||||
|
.ThenByDescending(x => x.DurationMs)
|
||||||
|
.Take(take)
|
||||||
|
.ToListAsync(ct);
|
||||||
|
|
||||||
|
return top.Select(x => new TopItem(x.Key, x.Label, x.Count, x.DurationMs / 1000d)).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IpProfile?> LookupIpAsync(string ip, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
var events = db.TrapEvents.AsNoTracking().Where(e => e.RemoteIp == ip);
|
||||||
|
|
||||||
|
var total = await events.CountAsync(ct);
|
||||||
|
if (total == 0)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var catches = events.Where(e => e.Outcome != TrapOutcome.Rejected);
|
||||||
|
var origin = await events.Where(e => e.CountryCode != null || e.Asn != null).OrderByDescending(e => e.Id).FirstOrDefaultAsync(ct);
|
||||||
|
var recent = await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).Take(MaxLimit).ToListAsync(ct);
|
||||||
|
|
||||||
|
return new IpProfile(
|
||||||
|
ip,
|
||||||
|
origin?.CountryCode,
|
||||||
|
origin?.Country,
|
||||||
|
origin?.City,
|
||||||
|
origin?.Asn,
|
||||||
|
origin?.Provider,
|
||||||
|
await catches.CountAsync(ct),
|
||||||
|
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct),
|
||||||
|
await catches.SumAsync(e => e.DurationMs, ct) / 1000d,
|
||||||
|
await events.SumAsync(e => e.BytesSent, ct),
|
||||||
|
await events.MinAsync(e => e.StartedAt, ct),
|
||||||
|
await events.MaxAsync(e => e.EndedAt, ct),
|
||||||
|
recent.Select(ToRecord).ToList(),
|
||||||
|
Math.Max(0, total - recent.Count));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IQueryable<TrapEventEntity> InPeriod(FlypaperDbContext db, DateTime? since)
|
||||||
|
{
|
||||||
|
var events = db.TrapEvents.AsNoTracking();
|
||||||
|
return since is { } start ? events.Where(e => e.StartedAt >= start) : events;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IQueryable<TrapEventEntity> ByProvider(IQueryable<TrapEventEntity> events, string provider)
|
||||||
|
{
|
||||||
|
var number = provider.StartsWith("AS", StringComparison.OrdinalIgnoreCase) ? provider[2..] : provider;
|
||||||
|
if (long.TryParse(number, NumberStyles.None, CultureInfo.InvariantCulture, out var asn))
|
||||||
|
{
|
||||||
|
return events.Where(e => e.Asn == asn);
|
||||||
|
}
|
||||||
|
|
||||||
|
var text = provider.ToLowerInvariant();
|
||||||
|
return events.Where(e => e.Provider != null && e.Provider.ToLower().Contains(text));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int Clamp(int limit) => Math.Clamp(limit, 1, MaxLimit);
|
||||||
|
|
||||||
|
private static CatchRecord ToRecord(TrapEventEntity e) => new(
|
||||||
|
e.Id,
|
||||||
|
e.StartedAt,
|
||||||
|
e.EndedAt,
|
||||||
|
e.DurationMs / 1000d,
|
||||||
|
e.BytesSent,
|
||||||
|
e.Outcome,
|
||||||
|
e.Strategy,
|
||||||
|
e.RemoteIp,
|
||||||
|
e.CountryCode,
|
||||||
|
e.Country,
|
||||||
|
e.City,
|
||||||
|
e.Asn,
|
||||||
|
e.Provider,
|
||||||
|
e.Target,
|
||||||
|
e.ClientInfo);
|
||||||
|
|
||||||
|
private sealed class TopRow
|
||||||
|
{
|
||||||
|
public required string Key { get; init; }
|
||||||
|
|
||||||
|
public string? Label { get; init; }
|
||||||
|
|
||||||
|
public int Count { get; init; }
|
||||||
|
|
||||||
|
public long DurationMs { get; init; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
using Flypaper.Core.Models;
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Queries;
|
||||||
|
|
||||||
|
public sealed record CatchRecord(
|
||||||
|
long Id,
|
||||||
|
DateTime StartedAt,
|
||||||
|
DateTime EndedAt,
|
||||||
|
double DurationSeconds,
|
||||||
|
long BytesSent,
|
||||||
|
TrapOutcome Outcome,
|
||||||
|
string Strategy,
|
||||||
|
string Ip,
|
||||||
|
string? CountryCode,
|
||||||
|
string? Country,
|
||||||
|
string? City,
|
||||||
|
long? Asn,
|
||||||
|
string? Provider,
|
||||||
|
string? Target,
|
||||||
|
string? UserAgent);
|
||||||
|
|
||||||
|
public sealed record CatchFilter(
|
||||||
|
DateTime? Since = null,
|
||||||
|
DateTime? Until = null,
|
||||||
|
string? Country = null,
|
||||||
|
string? Provider = null,
|
||||||
|
string? Ip = null,
|
||||||
|
string? TargetContains = null,
|
||||||
|
int Limit = 50);
|
||||||
|
|
||||||
|
public sealed record CatchStats(
|
||||||
|
int Catches,
|
||||||
|
int Rejected,
|
||||||
|
int UniqueIps,
|
||||||
|
double TotalHoldSeconds,
|
||||||
|
double AverageHoldSeconds,
|
||||||
|
CatchRecord? Longest);
|
||||||
|
|
||||||
|
public enum TopDimension
|
||||||
|
{
|
||||||
|
Ips,
|
||||||
|
Countries,
|
||||||
|
Providers,
|
||||||
|
Targets,
|
||||||
|
UserAgents
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record TopItem(string Key, string? Label, int Catches, double TotalHoldSeconds);
|
||||||
|
|
||||||
|
public sealed record IpProfile(
|
||||||
|
string Ip,
|
||||||
|
string? CountryCode,
|
||||||
|
string? Country,
|
||||||
|
string? City,
|
||||||
|
long? Asn,
|
||||||
|
string? Provider,
|
||||||
|
int Catches,
|
||||||
|
int Rejected,
|
||||||
|
double TotalHoldSeconds,
|
||||||
|
long TotalBytesSent,
|
||||||
|
DateTime? FirstSeen,
|
||||||
|
DateTime? LastSeen,
|
||||||
|
IReadOnlyList<CatchRecord> Events,
|
||||||
|
int EventsOmitted);
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Queries;
|
||||||
|
|
||||||
|
public static partial class QueryPeriod
|
||||||
|
{
|
||||||
|
[GeneratedRegex(@"^(\d{1,5})([mhdw])$", RegexOptions.IgnoreCase)]
|
||||||
|
private static partial Regex Pattern();
|
||||||
|
|
||||||
|
public static bool TryParse(string? value, out TimeSpan? span)
|
||||||
|
{
|
||||||
|
span = null;
|
||||||
|
var text = value?.Trim();
|
||||||
|
if (string.IsNullOrEmpty(text) || text.Equals("all", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
var match = Pattern().Match(text);
|
||||||
|
if (!match.Success)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var amount = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
|
||||||
|
span = char.ToLowerInvariant(match.Groups[2].Value[0]) switch
|
||||||
|
{
|
||||||
|
'm' => TimeSpan.FromMinutes(amount),
|
||||||
|
'h' => TimeSpan.FromHours(amount),
|
||||||
|
'd' => TimeSpan.FromDays(amount),
|
||||||
|
_ => TimeSpan.FromDays(amount * 7)
|
||||||
|
};
|
||||||
|
return amount > 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
using Flypaper.Storage.Entities;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Settings;
|
||||||
|
|
||||||
|
public sealed class AdminCredentialStore(IDbContextFactory<FlypaperDbContext> dbContextFactory)
|
||||||
|
{
|
||||||
|
private const string PasswordHashKey = "Flypaper:Admin:PasswordHash";
|
||||||
|
|
||||||
|
public async Task<string?> GetPasswordHashAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
return await db.Settings.Where(s => s.Key == PasswordHashKey).Select(s => s.Value).SingleOrDefaultAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> TryCreatePasswordHashAsync(string hash, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
db.Settings.Add(new SettingEntity { Key = PasswordHashKey, Value = hash });
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (DbUpdateException)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task UpdatePasswordHashAsync(string hash, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
var updated = await db.Settings
|
||||||
|
.Where(s => s.Key == PasswordHashKey)
|
||||||
|
.ExecuteUpdateAsync(setters => setters.SetProperty(s => s.Value, hash), ct);
|
||||||
|
if (updated == 0)
|
||||||
|
{
|
||||||
|
db.Settings.Add(new SettingEntity { Key = PasswordHashKey, Value = hash });
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
using Flypaper.Storage.Entities;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Flypaper.Storage.Settings;
|
||||||
|
|
||||||
|
public sealed class McpTokenStore(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
|
||||||
|
{
|
||||||
|
private static readonly TimeSpan LastUsedResolution = TimeSpan.FromMinutes(1);
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<McpTokenEntity>> ListAsync(CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
return await db.McpTokens.AsNoTracking().OrderBy(t => t.Id).ToListAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<McpTokenEntity> CreateAsync(string name, string tokenHash, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
var token = new McpTokenEntity { Name = name, TokenHash = tokenHash, CreatedAt = timeProvider.GetUtcNow().UtcDateTime };
|
||||||
|
db.McpTokens.Add(token);
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> RevokeAsync(int id, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
return await db.McpTokens.Where(t => t.Id == id).ExecuteDeleteAsync(ct) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<McpTokenEntity?> UseAsync(string tokenHash, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
var token = await db.McpTokens.SingleOrDefaultAsync(t => t.TokenHash == tokenHash, ct);
|
||||||
|
if (token is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var now = timeProvider.GetUtcNow().UtcDateTime;
|
||||||
|
if (token.LastUsedAt is null || now - token.LastUsedAt >= LastUsedResolution)
|
||||||
|
{
|
||||||
|
token.LastUsedAt = now;
|
||||||
|
await db.SaveChangesAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,28 +10,42 @@ public sealed partial class RuntimeSettingsStore(
|
|||||||
DbConfigurationSource source,
|
DbConfigurationSource source,
|
||||||
ILogger<RuntimeSettingsStore> logger)
|
ILogger<RuntimeSettingsStore> logger)
|
||||||
{
|
{
|
||||||
public async Task SaveAsync(RuntimeSettings settings, CancellationToken ct = default)
|
private static readonly string[] RuntimeKeys = SettingKeys.All.ToArray();
|
||||||
|
|
||||||
|
public Task SaveAsync(RuntimeSettings settings, CancellationToken ct = default) =>
|
||||||
|
SaveValuesAsync(settings.ToConfiguration(), ct);
|
||||||
|
|
||||||
|
public Task SaveAsync(HoldMethodSettings settings, CancellationToken ct = default) =>
|
||||||
|
SaveValuesAsync(settings.ToConfiguration(), ct);
|
||||||
|
|
||||||
|
public async Task ResetAsync(IReadOnlyCollection<string>? keys = null, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
await RuntimeSettings(db, keys).ExecuteDeleteAsync(ct);
|
||||||
|
Reload();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> HasOverridesAsync(IReadOnlyCollection<string>? keys = null, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
|
return await RuntimeSettings(db, keys).AnyAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SaveValuesAsync(IReadOnlyDictionary<string, string> values, CancellationToken ct)
|
||||||
{
|
{
|
||||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||||
await using var transaction = await db.Database.BeginTransactionAsync(ct);
|
await using var transaction = await db.Database.BeginTransactionAsync(ct);
|
||||||
await db.Settings.ExecuteDeleteAsync(ct);
|
await RuntimeSettings(db, values.Keys.ToArray()).ExecuteDeleteAsync(ct);
|
||||||
db.Settings.AddRange(settings.ToConfiguration().Select(pair => new SettingEntity { Key = pair.Key, Value = pair.Value }));
|
db.Settings.AddRange(values.Select(pair => new SettingEntity { Key = pair.Key, Value = pair.Value }));
|
||||||
await db.SaveChangesAsync(ct);
|
await db.SaveChangesAsync(ct);
|
||||||
await transaction.CommitAsync(ct);
|
await transaction.CommitAsync(ct);
|
||||||
Reload();
|
Reload();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task ResetAsync(CancellationToken ct = default)
|
private static IQueryable<SettingEntity> RuntimeSettings(FlypaperDbContext db, IReadOnlyCollection<string>? keys = null)
|
||||||
{
|
{
|
||||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
var selected = keys?.Where(key => SettingKeys.All.Contains(key)).ToArray() ?? RuntimeKeys;
|
||||||
await db.Settings.ExecuteDeleteAsync(ct);
|
return db.Settings.Where(setting => selected.Contains(setting.Key));
|
||||||
Reload();
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<bool> HasOverridesAsync(CancellationToken ct = default)
|
|
||||||
{
|
|
||||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
|
||||||
return await db.Settings.AnyAsync(ct);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void Reload()
|
private void Reload()
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
using System.Reflection;
|
||||||
|
|
||||||
|
namespace Flypaper.Web;
|
||||||
|
|
||||||
|
public static class AppVersion
|
||||||
|
{
|
||||||
|
public static string Current { get; } = Read();
|
||||||
|
|
||||||
|
private static string Read()
|
||||||
|
{
|
||||||
|
var version = typeof(AppVersion).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0-dev";
|
||||||
|
var plus = version.IndexOf('+');
|
||||||
|
return plus >= 0 && version.Length > plus + 8 ? version[..(plus + 8)] : version;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,22 +1,64 @@
|
|||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
using Flypaper.Storage.Settings;
|
||||||
|
using Microsoft.AspNetCore.Identity;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
namespace Flypaper.Web.Auth;
|
namespace Flypaper.Web.Auth;
|
||||||
|
|
||||||
public sealed class AdminAuthenticator(IOptions<AdminOptions> options)
|
public sealed class AdminAuthenticator(IOptions<AdminOptions> options, AdminCredentialStore store)
|
||||||
{
|
{
|
||||||
public bool IsConfigured => !string.IsNullOrEmpty(options.Value.Password);
|
public const int MinimumPasswordLength = 12;
|
||||||
|
|
||||||
public bool Verify(string? candidate)
|
private static readonly PasswordHasher<AdminAccount> Hasher = new();
|
||||||
|
private static readonly AdminAccount Account = new();
|
||||||
|
|
||||||
|
public bool UsesEnvironmentPassword => !string.IsNullOrEmpty(options.Value.Password);
|
||||||
|
|
||||||
|
public async Task<bool> IsConfiguredAsync(CancellationToken ct = default) =>
|
||||||
|
UsesEnvironmentPassword || await store.GetPasswordHashAsync(ct) is not null;
|
||||||
|
|
||||||
|
public async Task<bool> VerifyAsync(string? candidate, CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
if (!IsConfigured || string.IsNullOrEmpty(candidate))
|
if (string.IsNullOrEmpty(candidate))
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return CryptographicOperations.FixedTimeEquals(Hash(candidate), Hash(options.Value.Password!));
|
if (UsesEnvironmentPassword)
|
||||||
|
{
|
||||||
|
return CryptographicOperations.FixedTimeEquals(Sha256(candidate), Sha256(options.Value.Password!));
|
||||||
|
}
|
||||||
|
|
||||||
|
return await store.GetPasswordHashAsync(ct) is { } hash
|
||||||
|
&& Hasher.VerifyHashedPassword(Account, hash, candidate) != PasswordVerificationResult.Failed;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static byte[] Hash(string value) => SHA256.HashData(Encoding.UTF8.GetBytes(value));
|
public async Task<bool> TrySetInitialPasswordAsync(string password, CancellationToken ct = default) =>
|
||||||
|
!UsesEnvironmentPassword && await store.TryCreatePasswordHashAsync(Hasher.HashPassword(Account, password), ct);
|
||||||
|
|
||||||
|
public async Task<bool> TryChangePasswordAsync(string currentPassword, string newPassword, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
if (UsesEnvironmentPassword || !await VerifyAsync(currentPassword, ct))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
await store.UpdatePasswordHashAsync(Hasher.HashPassword(Account, newPassword), ct);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string? ValidateNewPassword(string? password, string? confirmation)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(password) || password.Length < MinimumPasswordLength)
|
||||||
|
{
|
||||||
|
return $"Mindestens {MinimumPasswordLength} Zeichen.";
|
||||||
|
}
|
||||||
|
|
||||||
|
return password == confirmation ? null : "Die Passwörter stimmen nicht überein.";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] Sha256(string value) => SHA256.HashData(Encoding.UTF8.GetBytes(value));
|
||||||
|
|
||||||
|
public sealed class AdminAccount;
|
||||||
}
|
}
|
||||||
@@ -18,17 +18,41 @@ public static class AuthEndpoints
|
|||||||
{
|
{
|
||||||
var target = IsLocalPath(returnUrl) ? returnUrl! : "/";
|
var target = IsLocalPath(returnUrl) ? returnUrl! : "/";
|
||||||
|
|
||||||
if (!admin.Verify(password))
|
if (!await admin.VerifyAsync(password, context.RequestAborted))
|
||||||
{
|
{
|
||||||
await Task.Delay(750, context.RequestAborted);
|
await Task.Delay(750, context.RequestAborted);
|
||||||
return Results.LocalRedirect($"/login?error=1&returnUrl={Uri.EscapeDataString(target)}");
|
return Results.LocalRedirect($"/login?error=1&returnUrl={Uri.EscapeDataString(target)}");
|
||||||
}
|
}
|
||||||
|
|
||||||
var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "admin")], CookieAuthenticationDefaults.AuthenticationScheme);
|
await SignInAsync(context);
|
||||||
await context.SignInAsync(new ClaimsPrincipal(identity));
|
|
||||||
return Results.LocalRedirect(target);
|
return Results.LocalRedirect(target);
|
||||||
}).AllowAnonymous();
|
}).AllowAnonymous();
|
||||||
|
|
||||||
|
app.MapPost("/auth/setup", async (
|
||||||
|
HttpContext context,
|
||||||
|
AdminAuthenticator admin,
|
||||||
|
[FromForm] string? password,
|
||||||
|
[FromForm] string? confirmation) =>
|
||||||
|
{
|
||||||
|
if (await admin.IsConfiguredAsync(context.RequestAborted))
|
||||||
|
{
|
||||||
|
return Results.LocalRedirect("/login");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (AdminAuthenticator.ValidateNewPassword(password, confirmation) is { } error)
|
||||||
|
{
|
||||||
|
return Results.LocalRedirect($"/setup?error={Uri.EscapeDataString(error)}");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!await admin.TrySetInitialPasswordAsync(password!, context.RequestAborted))
|
||||||
|
{
|
||||||
|
return Results.LocalRedirect("/login");
|
||||||
|
}
|
||||||
|
|
||||||
|
await SignInAsync(context);
|
||||||
|
return Results.LocalRedirect("/");
|
||||||
|
}).AllowAnonymous();
|
||||||
|
|
||||||
app.MapPost("/auth/logout", async (HttpContext context, IAntiforgery antiforgery) =>
|
app.MapPost("/auth/logout", async (HttpContext context, IAntiforgery antiforgery) =>
|
||||||
{
|
{
|
||||||
if (!await antiforgery.IsRequestValidAsync(context))
|
if (!await antiforgery.IsRequestValidAsync(context))
|
||||||
@@ -43,6 +67,12 @@ public static class AuthEndpoints
|
|||||||
return app;
|
return app;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static Task SignInAsync(HttpContext context)
|
||||||
|
{
|
||||||
|
var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "admin")], CookieAuthenticationDefaults.AuthenticationScheme);
|
||||||
|
return context.SignInAsync(new ClaimsPrincipal(identity));
|
||||||
|
}
|
||||||
|
|
||||||
private static bool IsLocalPath(string? url) =>
|
private static bool IsLocalPath(string? url) =>
|
||||||
!string.IsNullOrEmpty(url) && url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\'));
|
!string.IsNullOrEmpty(url) && url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\'));
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
<main class="page">
|
<main class="page">
|
||||||
<nav class="nav">
|
<nav class="nav">
|
||||||
|
<a href="/" class="brand"><span class="brand-mark" aria-hidden="true"></span>Flypaper</a>
|
||||||
<NavLink href="/" Match="NavLinkMatch.All">Dashboard</NavLink>
|
<NavLink href="/" Match="NavLinkMatch.All">Dashboard</NavLink>
|
||||||
<NavLink href="/settings">Einstellungen</NavLink>
|
<NavLink href="/settings">Einstellungen</NavLink>
|
||||||
<form method="post" action="/auth/logout" class="logout">
|
<form method="post" action="/auth/logout" class="logout">
|
||||||
@@ -11,6 +12,6 @@
|
|||||||
</nav>
|
</nav>
|
||||||
@Body
|
@Body
|
||||||
<footer class="footer">
|
<footer class="footer">
|
||||||
<a href="https://db-ip.com">IP Geolocation by DB-IP</a> (CC BY 4.0) · Kartendaten: Natural Earth
|
Flypaper @AppVersion.Current · <a href="https://db-ip.com">IP Geolocation by DB-IP</a> (CC BY 4.0) · Kartendaten: Natural Earth
|
||||||
</footer>
|
</footer>
|
||||||
</main>
|
</main>
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Net;
|
||||||
|
using Flypaper.Core.Models;
|
||||||
|
using Flypaper.Storage.Dashboard;
|
||||||
|
|
||||||
|
namespace Flypaper.Web.Components.Pages.Dashboard;
|
||||||
|
|
||||||
|
public sealed record DashboardFilter(
|
||||||
|
string? Zeit = null,
|
||||||
|
string? Ausgang = null,
|
||||||
|
string? Land = null,
|
||||||
|
string? Provider = null,
|
||||||
|
string? Ip = null,
|
||||||
|
string? Ziel = null,
|
||||||
|
string? Q = null,
|
||||||
|
int Limit = RecentFilter.DefaultLimit)
|
||||||
|
{
|
||||||
|
public const string Anchor = "faenge";
|
||||||
|
|
||||||
|
public static readonly IReadOnlyList<(string Value, string Label)> Periods = [("", "Alles"), ("24h", "24 h"), ("7d", "7 Tage")];
|
||||||
|
|
||||||
|
public static readonly IReadOnlyList<(string Value, string Label)> Outcomes =
|
||||||
|
[("", "Alle"), ("aufgegeben", "Aufgegeben"), ("zeitlimit", "Zeitlimit"), ("abgelehnt", "Abgelehnt")];
|
||||||
|
|
||||||
|
public bool IsEmpty => this with { Limit = RecentFilter.DefaultLimit } == new DashboardFilter();
|
||||||
|
|
||||||
|
public static DashboardFilter Parse(
|
||||||
|
string? zeit,
|
||||||
|
string? ausgang,
|
||||||
|
string? land,
|
||||||
|
string? provider,
|
||||||
|
string? ip,
|
||||||
|
string? ziel,
|
||||||
|
string? q,
|
||||||
|
string? limit)
|
||||||
|
{
|
||||||
|
var parsedLimit = int.TryParse(limit, NumberStyles.None, CultureInfo.InvariantCulture, out var value)
|
||||||
|
? Math.Clamp(value, 1, RecentFilter.MaxLimit)
|
||||||
|
: RecentFilter.DefaultLimit;
|
||||||
|
|
||||||
|
return new DashboardFilter(
|
||||||
|
Known(Periods, zeit),
|
||||||
|
Known(Outcomes, ausgang),
|
||||||
|
Clean(land) is { Length: 2 } country && country.All(char.IsAsciiLetter) ? country.ToUpperInvariant() : null,
|
||||||
|
Asn(provider) is { } asn ? $"AS{asn.ToString(CultureInfo.InvariantCulture)}" : null,
|
||||||
|
IPAddress.TryParse(Clean(ip), out var address) ? address.ToString() : null,
|
||||||
|
Clean(ziel),
|
||||||
|
Clean(q),
|
||||||
|
parsedLimit);
|
||||||
|
}
|
||||||
|
|
||||||
|
public RecentFilter ToRecentFilter() => new(
|
||||||
|
Zeit switch
|
||||||
|
{
|
||||||
|
"24h" => TimeSpan.FromHours(24),
|
||||||
|
"7d" => TimeSpan.FromDays(7),
|
||||||
|
_ => null
|
||||||
|
},
|
||||||
|
Ausgang switch
|
||||||
|
{
|
||||||
|
"aufgegeben" => TrapOutcome.ClientAborted,
|
||||||
|
"zeitlimit" => TrapOutcome.Timeout,
|
||||||
|
"abgelehnt" => TrapOutcome.Rejected,
|
||||||
|
_ => null
|
||||||
|
},
|
||||||
|
Land,
|
||||||
|
Asn(Provider),
|
||||||
|
Ip,
|
||||||
|
Ziel,
|
||||||
|
Q,
|
||||||
|
Limit);
|
||||||
|
|
||||||
|
public int NextLimit => Math.Min(Limit * 2, RecentFilter.MaxLimit);
|
||||||
|
|
||||||
|
public string Href(string anchor = Anchor)
|
||||||
|
{
|
||||||
|
var parts = new List<string>();
|
||||||
|
Add(parts, "zeit", Zeit);
|
||||||
|
Add(parts, "ausgang", Ausgang);
|
||||||
|
Add(parts, "land", Land);
|
||||||
|
Add(parts, "provider", Provider);
|
||||||
|
Add(parts, "ip", Ip);
|
||||||
|
Add(parts, "ziel", Ziel);
|
||||||
|
Add(parts, "q", Q);
|
||||||
|
if (Limit != RecentFilter.DefaultLimit)
|
||||||
|
{
|
||||||
|
Add(parts, "limit", Limit.ToString(CultureInfo.InvariantCulture));
|
||||||
|
}
|
||||||
|
|
||||||
|
return parts.Count == 0 ? $"/#{anchor}" : $"/?{string.Join("&", parts)}#{anchor}";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Add(List<string> parts, string name, string? value)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrEmpty(value))
|
||||||
|
{
|
||||||
|
parts.Add($"{name}={Uri.EscapeDataString(value)}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Known(IReadOnlyList<(string Value, string Label)> options, string? value)
|
||||||
|
{
|
||||||
|
var clean = Clean(value)?.ToLowerInvariant();
|
||||||
|
return clean is not null && options.Any(o => o.Value == clean) ? clean : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long? Asn(string? value)
|
||||||
|
{
|
||||||
|
var clean = Clean(value);
|
||||||
|
if (clean is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var digits = clean.StartsWith("AS", StringComparison.OrdinalIgnoreCase) ? clean[2..] : clean;
|
||||||
|
return long.TryParse(digits, NumberStyles.None, CultureInfo.InvariantCulture, out var asn) ? asn : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||||
|
}
|
||||||
@@ -1,107 +1,337 @@
|
|||||||
@page "/"
|
@page "/"
|
||||||
@using Flypaper.Core.Abstractions
|
@using Flypaper.Core.Abstractions
|
||||||
|
@using Flypaper.Core.Models
|
||||||
|
@using Flypaper.Http
|
||||||
|
@using Microsoft.Extensions.Options
|
||||||
@using Flypaper.Storage.Dashboard
|
@using Flypaper.Storage.Dashboard
|
||||||
@using Flypaper.Storage.Entities
|
@using Flypaper.Storage.Entities
|
||||||
@inject DashboardQueries Queries
|
@inject DashboardQueries Queries
|
||||||
@inject IConnectionGovernor Governor
|
@inject IConnectionGovernor Governor
|
||||||
|
@inject IOptions<PortOptions> Ports
|
||||||
|
|
||||||
<PageTitle>Flypaper</PageTitle>
|
<PageTitle>Flypaper</PageTitle>
|
||||||
<HeadContent>
|
<HeadContent>
|
||||||
<meta http-equiv="refresh" content="30" />
|
<meta http-equiv="refresh" content="30" />
|
||||||
</HeadContent>
|
</HeadContent>
|
||||||
|
|
||||||
<header class="top">
|
<header class="page-head">
|
||||||
<h1>Flypaper</h1>
|
<h1>Übersicht</h1>
|
||||||
<span class="muted">Stand @_loadedAt.ToString("HH:mm:ss") · aktualisiert alle 30 s</span>
|
<p><span class="live-dot" aria-hidden="true"></span>Stand @_loadedAt.ToString("HH:mm:ss") · aktualisiert alle 30 s</p>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@if (_data is { } data)
|
@if (_data is { } data)
|
||||||
{
|
{
|
||||||
|
var active = Governor.ActiveConnections;
|
||||||
|
var tabs = TopTabs(data);
|
||||||
<section class="metrics">
|
<section class="metrics">
|
||||||
<div class="metric"><span class="label">Fänge gesamt</span><span class="value">@data.TotalCatches.ToString("N0")</span></div>
|
<div class="metric @(active > 0 ? "live" : null)">
|
||||||
<div class="metric"><span class="label">Letzte 24 h</span><span class="value">@data.CatchesLast24Hours.ToString("N0")</span></div>
|
<span class="label">Gerade in der Falle</span>
|
||||||
<div class="metric"><span class="label">Aktiv</span><span class="value">@Governor.ActiveConnections.ToString("N0")</span></div>
|
<span class="value">@Formatting.Number(active)</span>
|
||||||
<div class="metric"><span class="label">Eindeutige IPs</span><span class="value">@data.UniqueIps.ToString("N0")</span></div>
|
<span class="sub">@(active == 1 ? "Bot festgehalten" : "Bots festgehalten")</span>
|
||||||
<div class="metric"><span class="label">Haltezeit gesamt</span><span class="value">@Formatting.Duration(data.TotalHoldTime)</span></div>
|
</div>
|
||||||
<div class="metric"><span class="label">Abgelehnt</span><span class="value">@data.Rejected.ToString("N0")</span></div>
|
<div class="metric">
|
||||||
|
<span class="label">Fänge gesamt</span>
|
||||||
|
<span class="value">@Formatting.Number(data.TotalCatches)</span>
|
||||||
|
<span class="sub">+@Formatting.Number(data.CatchesLast24Hours) in 24 h</span>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<span class="label">Eindeutige IPs</span>
|
||||||
|
<span class="value">@Formatting.Number(data.UniqueIps)</span>
|
||||||
|
<span class="sub">@Formatting.Number(data.UniqueIpsLast24Hours) in 24 h aktiv</span>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<span class="label">Haltezeit gesamt</span>
|
||||||
|
<span class="value">@Formatting.Duration(data.TotalHoldTime)</span>
|
||||||
|
<span class="sub">Ø @(data.TotalCatches == 0 ? "–" : Formatting.Duration(data.TotalHoldTime / data.TotalCatches)) pro Fang</span>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<span class="label">Abgelehnt</span>
|
||||||
|
<span class="value">@Formatting.Number(data.Rejected)</span>
|
||||||
|
<span class="sub">+@Formatting.Number(data.RejectedLast24Hours) in 24 h · Limit erreicht</span>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<WorldMap CatchesByCountry="data.CatchesByCountry" />
|
@if (data.TotalCatches == 0)
|
||||||
|
{
|
||||||
|
<section class="card onboarding">
|
||||||
|
<h2>Noch keine Fänge</h2>
|
||||||
|
<p class="muted">Flypaper wartet. Sobald dein Reverse Proxy unbekannte Hosts weiterleitet, tauchen hier die ersten Bots auf.</p>
|
||||||
|
<ol>
|
||||||
|
<li>Leite den Catch-all- bzw. Default-Server deines Proxys auf den Trap-Port <code>@Ports.Value.Trap</code>.</li>
|
||||||
|
<li>Setze dort <code>X-Real-IP</code> und schalte das Response-Buffering ab.</li>
|
||||||
|
<li>Teste die Falle mit <code>curl -N http://<host>:@Ports.Value.Trap/.env</code>.</li>
|
||||||
|
</ol>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
<section class="tops">
|
<section class="origin">
|
||||||
<TopTable Title="Top 10 Länder" KeyLabel="Land" Entries="data.TopCountries" ShowFlags="true" />
|
<WorldMap CatchesByCountry="data.CatchesByCountry" />
|
||||||
<TopTable Title="Top 10 Provider (ASN)" KeyLabel="Provider" Entries="data.TopProviders" />
|
<section class="card tops-card">
|
||||||
<TopTable Title="Top 10 IPs" KeyLabel="IP" Entries="data.TopIps" />
|
<div class="card-head">
|
||||||
<TopTable Title="Top 10 Ziele" KeyLabel="Ziel" Entries="data.TopTargets" />
|
<h2 id="tops-title">Top 10</h2>
|
||||||
</section>
|
<span class="hint">Klick filtert die Fänge</span>
|
||||||
|
|
||||||
<section class="card">
|
|
||||||
<h2>Letzte 50 Fänge <span class="hint">Zeile anklicken zum Aufklappen</span></h2>
|
|
||||||
@if (data.Recent.Count == 0)
|
|
||||||
{
|
|
||||||
<p class="muted">Noch nichts gefangen.</p>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<div class="scroll">
|
|
||||||
<table class="recent-table">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Zeit</th>
|
|
||||||
<th>IP</th>
|
|
||||||
<th>Herkunft</th>
|
|
||||||
<th>Provider</th>
|
|
||||||
<th>Ziel</th>
|
|
||||||
<th>User-Agent</th>
|
|
||||||
<th class="num">Dauer</th>
|
|
||||||
<th class="num">Bytes</th>
|
|
||||||
<th>Ausgang</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
@foreach (var trapEvent in data.Recent)
|
|
||||||
{
|
|
||||||
<tr data-expand="event:@trapEvent.Id" tabindex="0" aria-expanded="false">
|
|
||||||
<td class="nowrap">@trapEvent.StartedAt.ToLocalTime().ToString("dd.MM. HH:mm:ss")</td>
|
|
||||||
<td class="mono">@trapEvent.RemoteIp</td>
|
|
||||||
<td class="nowrap" title="@Origin(trapEvent)">
|
|
||||||
@if (trapEvent.CountryCode is { } countryCode)
|
|
||||||
{
|
|
||||||
@($"{Formatting.Flag(countryCode)} {countryCode}")
|
|
||||||
<span class="detail">@Origin(trapEvent)</span>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<span class="muted">–</span>
|
|
||||||
}
|
|
||||||
</td>
|
|
||||||
<td class="clip" title="@Formatting.Provider(trapEvent.Asn, trapEvent.Provider)">@Formatting.Provider(trapEvent.Asn, trapEvent.Provider)</td>
|
|
||||||
<td class="mono clip" title="@trapEvent.Target">@trapEvent.Target</td>
|
|
||||||
<td class="clip" title="@trapEvent.ClientInfo">@trapEvent.ClientInfo</td>
|
|
||||||
<td class="num">@Formatting.Duration(TimeSpan.FromMilliseconds(trapEvent.DurationMs))</td>
|
|
||||||
<td class="num">@trapEvent.BytesSent.ToString("N0")</td>
|
|
||||||
<td><span class="outcome @trapEvent.Outcome.ToString().ToLowerInvariant()">@trapEvent.Outcome</span></td>
|
|
||||||
</tr>
|
|
||||||
}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
</div>
|
||||||
}
|
<div class="tabs" role="tablist" aria-labelledby="tops-title">
|
||||||
|
@foreach (var tab in tabs)
|
||||||
|
{
|
||||||
|
var first = tab == tabs[0];
|
||||||
|
<button type="button" role="tab" id="tab-@tab.Id" aria-controls="panel-@tab.Id" aria-selected="@(first ? "true" : "false")" tabindex="@(first ? 0 : -1)">@tab.Label</button>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
@foreach (var tab in tabs)
|
||||||
|
{
|
||||||
|
<div role="tabpanel" id="panel-@tab.Id" aria-labelledby="tab-@tab.Id" tabindex="0" hidden="@(tab != tabs[0])">
|
||||||
|
<TopTable KeyLabel="@tab.KeyLabel" Entries="tab.Entries" ShowFlags="tab.ShowFlags" KeyFormatter="tab.KeyFormatter" LabelFormatter="tab.LabelFormatter"
|
||||||
|
Href="entry => TopFilter(tab, entry).Href()" IsActive="entry => tab.Current(_filter) == entry.Key" />
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
@if (data.TotalCatches > 0 || data.Rejected > 0)
|
||||||
|
{
|
||||||
|
var recent = _recent!;
|
||||||
|
<section class="card recent-card" id="@DashboardFilter.Anchor">
|
||||||
|
<div class="card-head">
|
||||||
|
<h2>Fänge <span class="count">· @Formatting.Number(recent.Total) Treffer</span></h2>
|
||||||
|
<span class="hint">Filter gelten nur für diese Liste</span>
|
||||||
|
</div>
|
||||||
|
<form class="filters" method="get" action="/#@DashboardFilter.Anchor">
|
||||||
|
<label>
|
||||||
|
<span>Zeitraum</span>
|
||||||
|
<select name="zeit" data-autosubmit>
|
||||||
|
@foreach (var (value, label) in DashboardFilter.Periods)
|
||||||
|
{
|
||||||
|
<option value="@value" selected="@(value == (_filter.Zeit ?? ""))">@label</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<span>Ausgang</span>
|
||||||
|
<select name="ausgang" data-autosubmit>
|
||||||
|
@foreach (var (value, label) in DashboardFilter.Outcomes)
|
||||||
|
{
|
||||||
|
<option value="@value" selected="@(value == (_filter.Ausgang ?? ""))">@label</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<span>Land</span>
|
||||||
|
<select name="land" data-autosubmit>
|
||||||
|
<option value="" selected="@(_filter.Land is null)">Alle</option>
|
||||||
|
@foreach (var country in recent.Countries.OrderBy(c => CountryNames.Display(c.Code, c.Name), StringComparer.CurrentCulture))
|
||||||
|
{
|
||||||
|
<option value="@country.Code" selected="@(country.Code == _filter.Land)">@Formatting.Flag(country.Code) @CountryNames.Display(country.Code, country.Name)</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="filter-search">
|
||||||
|
<span>Suche</span>
|
||||||
|
<input type="search" name="q" value="@_filter.Q" placeholder="IP, Provider, Ziel, User-Agent" />
|
||||||
|
</label>
|
||||||
|
@foreach (var (name, value) in new[] { ("provider", _filter.Provider), ("ip", _filter.Ip), ("ziel", _filter.Ziel) })
|
||||||
|
{
|
||||||
|
if (value is not null)
|
||||||
|
{
|
||||||
|
<input type="hidden" name="@name" value="@value" />
|
||||||
|
}
|
||||||
|
}
|
||||||
|
<button type="submit">Filtern</button>
|
||||||
|
</form>
|
||||||
|
@if (!_filter.IsEmpty)
|
||||||
|
{
|
||||||
|
<div class="chips">
|
||||||
|
@foreach (var (label, without) in Chips())
|
||||||
|
{
|
||||||
|
<a class="chip" href="@without.Href()" title="Filter entfernen">@label <span aria-hidden="true">✕</span></a>
|
||||||
|
}
|
||||||
|
<a class="chip-reset" href="@(new DashboardFilter().Href())">Alle Filter zurücksetzen</a>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
@if (recent.Items.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="empty">Keine Fänge für diese Filter. <a href="@(new DashboardFilter().Href())">Filter zurücksetzen</a></p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="scroll">
|
||||||
|
<table class="recent-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th class="c-time">Zeit</th>
|
||||||
|
<th class="c-ip">IP</th>
|
||||||
|
<th class="c-origin">Herkunft</th>
|
||||||
|
<th class="c-provider">Provider</th>
|
||||||
|
<th class="c-target">Ziel</th>
|
||||||
|
<th class="c-agent">User-Agent</th>
|
||||||
|
<th class="c-duration num">Dauer</th>
|
||||||
|
<th class="c-bytes num">Bytes</th>
|
||||||
|
<th class="c-outcome">Ausgang</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var (trapEvent, index) in recent.Items.Select((trapEvent, index) => (trapEvent, index)))
|
||||||
|
{
|
||||||
|
var started = trapEvent.StartedAt.ToLocalTime();
|
||||||
|
var provider = Formatting.Provider(trapEvent.Asn, trapEvent.Provider);
|
||||||
|
var target = Formatting.Target(trapEvent.Target);
|
||||||
|
var duration = Formatting.Duration(TimeSpan.FromMilliseconds(trapEvent.DurationMs));
|
||||||
|
var bytes = Formatting.Number(trapEvent.BytesSent);
|
||||||
|
<tr id="f@(index)" data-expand="event:@trapEvent.Id" tabindex="0" aria-expanded="false" class="@(trapEvent.Outcome == TrapOutcome.Rejected ? "rejected" : null)">
|
||||||
|
<td class="c-time"><span class="c-date">@started.ToString("dd.MM.") </span>@started.ToString("HH:mm:ss")</td>
|
||||||
|
<td class="c-ip mono" title="@trapEvent.RemoteIp">@trapEvent.RemoteIp</td>
|
||||||
|
<td class="c-origin" title="@Origin(trapEvent)">
|
||||||
|
@if (trapEvent.CountryCode is { } countryCode)
|
||||||
|
{
|
||||||
|
@($"{Formatting.Flag(countryCode)} {countryCode}")
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<span class="muted">–</span>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
<td class="c-provider" title="@provider">@provider</td>
|
||||||
|
<td class="c-target mono" title="@target">
|
||||||
|
@target
|
||||||
|
<div class="extra extra-md">Provider: @(provider ?? "–")</div>
|
||||||
|
<div class="extra extra-md">User-Agent: @(trapEvent.ClientInfo ?? "–")</div>
|
||||||
|
<div class="extra extra-all">Herkunft: @(trapEvent.CountryCode is { } code ? $"{Formatting.Flag(code)} {code} · {Origin(trapEvent)}" : "–")</div>
|
||||||
|
<div class="extra extra-sm">Dauer: @duration · Bytes: @bytes</div>
|
||||||
|
<div class="extra extra-xs">Datum: @started.ToString("dd.MM.yyyy") · Ausgang: @OutcomeLabel(trapEvent.Outcome)</div>
|
||||||
|
</td>
|
||||||
|
<td class="c-agent" title="@trapEvent.ClientInfo">@trapEvent.ClientInfo</td>
|
||||||
|
<td class="c-duration num">@duration</td>
|
||||||
|
<td class="c-bytes num">@bytes</td>
|
||||||
|
<td class="c-outcome"><span class="outcome @trapEvent.Outcome.ToString().ToLowerInvariant()">@OutcomeLabel(trapEvent.Outcome)</span></td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
@if (recent.Total > recent.Items.Count)
|
||||||
|
{
|
||||||
|
<div class="more">
|
||||||
|
<span class="muted">@Formatting.Number(recent.Items.Count) von @Formatting.Number(recent.Total)</span>
|
||||||
|
@if (_filter.Limit < RecentFilter.MaxLimit)
|
||||||
|
{
|
||||||
|
<a class="button ghost" href="@((_filter with { Limit = _filter.NextLimit }).Href($"f{recent.Items.Count}"))">Weitere laden</a>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<span class="muted">· Für ältere Fänge die Filter eingrenzen</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
<script src="@Assets["dashboard.js"]" defer></script>
|
<script src="@Assets["dashboard.js"]" defer></script>
|
||||||
|
|
||||||
@code {
|
@code {
|
||||||
private DashboardData? _data;
|
private DashboardData? _data;
|
||||||
|
private RecentCatches? _recent;
|
||||||
|
private DashboardFilter _filter = new();
|
||||||
private DateTime _loadedAt;
|
private DateTime _loadedAt;
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "zeit")] public string? Zeit { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "ausgang")] public string? Ausgang { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "land")] public string? Land { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "provider")] public string? Provider { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "ip")] public string? Ip { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "ziel")] public string? Ziel { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "q")] public string? Q { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "limit")] public string? Limit { get; set; }
|
||||||
|
|
||||||
protected override async Task OnInitializedAsync()
|
protected override async Task OnInitializedAsync()
|
||||||
{
|
{
|
||||||
|
_filter = DashboardFilter.Parse(Zeit, Ausgang, Land, Provider, Ip, Ziel, Q, Limit);
|
||||||
_data = await Queries.GetAsync();
|
_data = await Queries.GetAsync();
|
||||||
|
_recent = await Queries.GetRecentAsync(_filter.ToRecentFilter());
|
||||||
_loadedAt = DateTime.Now;
|
_loadedAt = DateTime.Now;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static IReadOnlyList<TopTab> TopTabs(DashboardData data) =>
|
||||||
|
[
|
||||||
|
new("countries", "Länder", "Land", data.TopCountries, f => f.Land, (f, key) => f with { Land = key }, ShowFlags: true, LabelFormatter: CountryNames.Display),
|
||||||
|
new("providers", "Provider", "Provider", data.TopProviders, f => f.Provider, (f, key) => f with { Provider = key }),
|
||||||
|
new("ips", "IPs", "IP", data.TopIps, f => f.Ip, (f, key) => f with { Ip = key }),
|
||||||
|
new("targets", "Ziele", "Ziel", data.TopTargets, f => f.Ziel, (f, key) => f with { Ziel = key }, KeyFormatter: Formatting.Target)
|
||||||
|
];
|
||||||
|
|
||||||
|
private DashboardFilter TopFilter(TopTab tab, TopEntry entry) =>
|
||||||
|
tab.Set(_filter with { Limit = RecentFilter.DefaultLimit }, tab.Current(_filter) == entry.Key ? null : entry.Key);
|
||||||
|
|
||||||
|
private IEnumerable<(string Label, DashboardFilter Without)> Chips()
|
||||||
|
{
|
||||||
|
var reset = _filter with { Limit = RecentFilter.DefaultLimit };
|
||||||
|
if (_filter.Zeit is { } zeit)
|
||||||
|
{
|
||||||
|
yield return ($"Zeitraum: {DashboardFilter.Periods.First(p => p.Value == zeit).Label}", reset with { Zeit = null });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_filter.Ausgang is { } ausgang)
|
||||||
|
{
|
||||||
|
yield return ($"Ausgang: {DashboardFilter.Outcomes.First(o => o.Value == ausgang).Label}", reset with { Ausgang = null });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_filter.Land is { } land)
|
||||||
|
{
|
||||||
|
var name = _recent?.Countries.FirstOrDefault(c => c.Code == land)?.Name;
|
||||||
|
yield return ($"Land: {CountryNames.Display(land, name)}", reset with { Land = null });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_filter.Provider is { } provider)
|
||||||
|
{
|
||||||
|
var name = _data?.TopProviders.FirstOrDefault(p => p.Key == provider)?.Label
|
||||||
|
?? _recent?.Items.FirstOrDefault()?.Provider;
|
||||||
|
yield return ($"Provider: {(name is null ? provider : $"{name} ({provider})")}", reset with { Provider = null });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_filter.Ip is { } ip)
|
||||||
|
{
|
||||||
|
yield return ($"IP: {ip}", reset with { Ip = null });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_filter.Ziel is { } ziel)
|
||||||
|
{
|
||||||
|
yield return ($"Ziel: {Formatting.Target(ziel)}", reset with { Ziel = null });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_filter.Q is { } q)
|
||||||
|
{
|
||||||
|
yield return ($"Suche: „{q}“", reset with { Q = null });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string OutcomeLabel(TrapOutcome outcome) => outcome switch
|
||||||
|
{
|
||||||
|
TrapOutcome.Timeout => "Zeitlimit",
|
||||||
|
TrapOutcome.ClientAborted => "Aufgegeben",
|
||||||
|
TrapOutcome.Rejected => "Abgelehnt",
|
||||||
|
TrapOutcome.Completed => "Beendet",
|
||||||
|
_ => outcome.ToString()
|
||||||
|
};
|
||||||
|
|
||||||
private static string Origin(TrapEventEntity trapEvent) =>
|
private static string Origin(TrapEventEntity trapEvent) =>
|
||||||
string.Join(", ", new[] { trapEvent.City, trapEvent.Country }.Where(part => !string.IsNullOrEmpty(part)));
|
string.Join(", ", new[] { trapEvent.City, CountryNames.Display(trapEvent.CountryCode, trapEvent.Country) }.Where(part => !string.IsNullOrEmpty(part)));
|
||||||
|
|
||||||
|
private sealed record TopTab(
|
||||||
|
string Id,
|
||||||
|
string Label,
|
||||||
|
string KeyLabel,
|
||||||
|
IReadOnlyList<TopEntry> Entries,
|
||||||
|
Func<DashboardFilter, string?> Current,
|
||||||
|
Func<DashboardFilter, string?, DashboardFilter> Set,
|
||||||
|
bool ShowFlags = false,
|
||||||
|
Func<string?, string?>? KeyFormatter = null,
|
||||||
|
Func<string?, string?, string?>? LabelFormatter = null);
|
||||||
}
|
}
|
||||||
@@ -1,47 +1,74 @@
|
|||||||
|
@using System.Globalization
|
||||||
@using Flypaper.Storage.Dashboard
|
@using Flypaper.Storage.Dashboard
|
||||||
<section class="card">
|
|
||||||
<h2>@Title</h2>
|
@if (Entries.Count == 0)
|
||||||
@if (Entries.Count == 0)
|
{
|
||||||
{
|
<p class="empty">Noch keine Einträge.</p>
|
||||||
<p class="muted">Keine Daten.</p>
|
}
|
||||||
}
|
else
|
||||||
else
|
{
|
||||||
{
|
<table class="top-table">
|
||||||
<table class="top-table">
|
<colgroup>
|
||||||
<colgroup>
|
<col />
|
||||||
<col />
|
<col class="share" />
|
||||||
<col class="count" />
|
<col class="count" />
|
||||||
<col class="hold" />
|
<col class="hold" />
|
||||||
</colgroup>
|
</colgroup>
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
<th>@KeyLabel</th>
|
<th>@KeyLabel</th>
|
||||||
<th class="num">Fänge</th>
|
<th><span class="sr-only">Anteil</span></th>
|
||||||
<th class="num">Haltezeit</th>
|
<th class="num">Fänge</th>
|
||||||
|
<th class="num">Haltezeit</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var entry in Entries)
|
||||||
|
{
|
||||||
|
var key = KeyFormatter?.Invoke(entry.Key) ?? entry.Key;
|
||||||
|
var label = LabelFormatter is null ? entry.Label : LabelFormatter(entry.Key, entry.Label);
|
||||||
|
var share = (entry.Count * 100.0 / Entries[0].Count).ToString("0.#", CultureInfo.InvariantCulture);
|
||||||
|
var active = IsActive(entry);
|
||||||
|
var title = label is null ? key : $"{label} · {key}";
|
||||||
|
<tr data-href="@Href(entry)" class="@(active ? "active" : null)">
|
||||||
|
<td class="clip" title="@title">
|
||||||
|
<a href="@Href(entry)" aria-current="@(active ? "true" : null)" title="@(active ? $"Filter {title} entfernen" : $"Fänge filtern: {title}")">
|
||||||
|
@if (ShowFlags)
|
||||||
|
{
|
||||||
|
<span class="flag">@Formatting.Flag(entry.Key)</span>
|
||||||
|
}
|
||||||
|
@if (label is not null)
|
||||||
|
{
|
||||||
|
<span class="top-label">@label</span>
|
||||||
|
<span class="top-key mono">@key</span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<span class="mono">@key</span>
|
||||||
|
}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td><span class="share-bar" style="--share: @(share)%"></span></td>
|
||||||
|
<td class="num">@Formatting.Number(entry.Count)</td>
|
||||||
|
<td class="num">@Formatting.Duration(entry.HoldTime)</td>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
}
|
||||||
<tbody>
|
</tbody>
|
||||||
@foreach (var entry in Entries)
|
</table>
|
||||||
{
|
}
|
||||||
<tr data-expand="@($"{KeyLabel}:{entry.Key}")" tabindex="0" aria-expanded="false">
|
|
||||||
<td class="mono clip" title="@Display(entry)">@(ShowFlags ? $"{Formatting.Flag(entry.Key)} " : "")@Display(entry)</td>
|
|
||||||
<td class="num">@entry.Count.ToString("N0")</td>
|
|
||||||
<td class="num">@Formatting.Duration(entry.HoldTime)</td>
|
|
||||||
</tr>
|
|
||||||
}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
}
|
|
||||||
</section>
|
|
||||||
|
|
||||||
@code {
|
@code {
|
||||||
[Parameter, EditorRequired] public required string Title { get; set; }
|
|
||||||
|
|
||||||
[Parameter, EditorRequired] public required string KeyLabel { get; set; }
|
[Parameter, EditorRequired] public required string KeyLabel { get; set; }
|
||||||
|
|
||||||
[Parameter, EditorRequired] public required IReadOnlyList<TopEntry> Entries { get; set; }
|
[Parameter, EditorRequired] public required IReadOnlyList<TopEntry> Entries { get; set; }
|
||||||
|
|
||||||
[Parameter] public bool ShowFlags { get; set; }
|
[Parameter] public bool ShowFlags { get; set; }
|
||||||
|
|
||||||
private static string Display(TopEntry entry) => entry.Label is null ? entry.Key : $"{entry.Key} · {entry.Label}";
|
[Parameter] public Func<string?, string?>? KeyFormatter { get; set; }
|
||||||
|
|
||||||
|
[Parameter] public Func<string?, string?, string?>? LabelFormatter { get; set; }
|
||||||
|
|
||||||
|
[Parameter, EditorRequired] public required Func<TopEntry, string> Href { get; set; }
|
||||||
|
|
||||||
|
[Parameter, EditorRequired] public required Func<TopEntry, bool> IsActive { get; set; }
|
||||||
}
|
}
|
||||||
@@ -1,21 +1,47 @@
|
|||||||
@using System.Globalization
|
@using System.Globalization
|
||||||
|
|
||||||
<section class="card">
|
<section class="card map-card">
|
||||||
<h2>Herkunft</h2>
|
<div class="card-head">
|
||||||
<svg class="world-map" viewBox="0 0 @Map.Width.ToString(CultureInfo.InvariantCulture) @Map.Height.ToString(CultureInfo.InvariantCulture)" role="img" aria-label="Weltkarte der Fänge nach Land">
|
<h2>Herkunft</h2>
|
||||||
@foreach (var country in Map.Countries)
|
@if (_max > 0)
|
||||||
{
|
{
|
||||||
var count = Count(country.Code);
|
<div class="map-legend" aria-label="Fänge pro Land">
|
||||||
<path d="@country.Path" class="@($"level-{Level(count)}")"><title>@country.Name: @count.ToString("N0") @(count == 1 ? "Fang" : "Fänge")</title></path>
|
<span class="swatch level-0" title="keine"></span>
|
||||||
|
<span>1</span>
|
||||||
|
@for (var level = 1; level <= Levels; level++)
|
||||||
|
{
|
||||||
|
<span class="swatch @($"level-{level}")"></span>
|
||||||
|
}
|
||||||
|
<span>@Formatting.Number(_max)</span>
|
||||||
|
</div>
|
||||||
}
|
}
|
||||||
</svg>
|
</div>
|
||||||
<div class="map-legend">
|
<div class="map-wrap">
|
||||||
<span>0</span>
|
<svg class="world-map" viewBox="0 0 @Map.Width.ToString(CultureInfo.InvariantCulture) @Map.Height.ToString(CultureInfo.InvariantCulture)" role="img" aria-label="Weltkarte der Fänge nach Land">
|
||||||
@for (var level = 0; level <= Levels; level++)
|
@foreach (var country in Map.Countries)
|
||||||
|
{
|
||||||
|
var count = Count(country.Code);
|
||||||
|
<path d="@country.Path" class="@($"level-{Level(count)}")"><title>@Title(CountryNames.Display(country.Code, country.Name)!, count)</title></path>
|
||||||
|
}
|
||||||
|
@foreach (var marker in Map.Markers)
|
||||||
|
{
|
||||||
|
var count = Count(marker.Code);
|
||||||
|
if (count > 0)
|
||||||
|
{
|
||||||
|
var x = marker.X.ToString(CultureInfo.InvariantCulture);
|
||||||
|
var y = marker.Y.ToString(CultureInfo.InvariantCulture);
|
||||||
|
<g class="@($"marker level-{Level(count)}")">
|
||||||
|
<title>@Title(CountryNames.Display(marker.Code, marker.Name)!, count)</title>
|
||||||
|
<circle class="hit" cx="@x" cy="@y" r="14" />
|
||||||
|
<circle class="dot" cx="@x" cy="@y" r="6" />
|
||||||
|
</g>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</svg>
|
||||||
|
@if (_max == 0)
|
||||||
{
|
{
|
||||||
<span class="swatch @($"level-{level}")"></span>
|
<p class="map-empty">Sobald Bots anklopfen, färbt sich die Karte nach Herkunftsland.</p>
|
||||||
}
|
}
|
||||||
<span>@_max.ToString("N0")</span>
|
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -31,6 +57,8 @@
|
|||||||
|
|
||||||
private int Count(string? code) => code is not null && CatchesByCountry.TryGetValue(code, out var count) ? count : 0;
|
private int Count(string? code) => code is not null && CatchesByCountry.TryGetValue(code, out var count) ? count : 0;
|
||||||
|
|
||||||
|
private static string Title(string name, int count) => $"{name}: {count:N0} {(count == 1 ? "Fang" : "Fänge")}";
|
||||||
|
|
||||||
private int Level(int count) =>
|
private int Level(int count) =>
|
||||||
count == 0 || _max == 0 ? 0 : Math.Max(1, (int)Math.Ceiling(Math.Log(count + 1) / Math.Log(_max + 1) * Levels));
|
count == 0 || _max == 0 ? 0 : Math.Max(1, (int)Math.Ceiling(Math.Log(count + 1) / Math.Log(_max + 1) * Levels));
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,11 @@ using System.Text.Json;
|
|||||||
|
|
||||||
namespace Flypaper.Web.Components.Pages.Dashboard;
|
namespace Flypaper.Web.Components.Pages.Dashboard;
|
||||||
|
|
||||||
internal sealed record WorldMapData(double Width, double Height, IReadOnlyList<WorldMapCountry> Countries)
|
internal sealed record WorldMapData(
|
||||||
|
double Width,
|
||||||
|
double Height,
|
||||||
|
IReadOnlyList<WorldMapCountry> Countries,
|
||||||
|
IReadOnlyList<WorldMapMarker> Markers)
|
||||||
{
|
{
|
||||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||||
|
|
||||||
@@ -18,3 +22,5 @@ internal sealed record WorldMapData(double Width, double Height, IReadOnlyList<W
|
|||||||
}
|
}
|
||||||
|
|
||||||
internal sealed record WorldMapCountry(string? Code, string Name, string Path);
|
internal sealed record WorldMapCountry(string? Code, string Name, string Path);
|
||||||
|
|
||||||
|
internal sealed record WorldMapMarker(string Code, string Name, double X, double Y);
|
||||||
@@ -1 +1 @@
|
|||||||
{"width":1000.0,"height":439.1,"countries":[{"code":"AF","name":"Afghanistan","path":"M669.6,108.7L671,108.7L673.1,109.4L674,109.9L675.5,108.8L676.6,109.4L677,107.9L678.5,108L678.7,107.5L678.6,106.1L679.3,104.9L680.9,105.7L681,106.7L681.8,106.9L682.4,109.7L683.8,110.8L684.5,110.1L685.5,109.8L686.6,108.3L688.4,108.5L691.1,108.5L691.8,109.5L690.5,109.9L689.4,110.5L686.6,110.9L684,111.6L683,113.1L684,114.5L684.8,116.2L683.9,117.6L684.4,119L684.1,120.2L681.6,120.1L683.2,122.4L681.8,123.3L681.2,125.4L681.9,127.5L681.1,128.4L680.1,128.1L678.2,128.6L678.1,129.5L676.2,129.5L675.2,131.5L675.8,134.5L672.6,136L670.7,135.7L670.4,136.5L668.7,136L666.1,136.5L661.3,134.7L663,131.5L662.3,129.3L660.2,128.7L659.5,126.5L658,123.7L658.7,121.8L657.4,121.3L657.6,118.8L657.5,114.5L660.5,115.8L662.3,115.4L662.5,113.8L664.4,113.3L665.5,112.3L665.3,109.6L667.2,108.9L667.3,107.7L668.8,108.6L669.6,108.7Z"},{"code":"AL","name":"Albanien","path":"M552.5,97.2L552.5,98L551.7,98.5L551.7,99.6L550.7,101.2L550.2,100.9L550.1,100.2L548.6,99.1L548.2,97.5L548.2,95.3L548.5,94.3L548,93.8L547.8,92.8L548.7,91.2L548.9,91.8L549.5,91.5L550.1,92.4L550.8,92.7L551,93.9L550.8,95L551.3,96.4L552.5,97.2Z"},{"code":"DZ","name":"Algerien","path":"M476.7,143.4L476.8,142.7L476.8,142.5L476.9,138.2L481.3,135.6L483.9,135.1L486.1,134.1L487.2,132.4L490.3,131L490.4,128.4L491.9,128.1L493.1,126.8L496.6,126.2L497.1,124.8L496.4,124.1L495.5,120.4L495.4,118.4L494.4,116.2L496.9,114.3L499.7,113.7L501.3,112.3L503.8,111.3L508.1,110.7L512.3,110.4L513.6,110.9L516,109.6L518.7,109.5L519.8,110.3L521.5,110.1L521.1,111.9L521.6,115.1L521.1,117.9L519.5,119.8L519.8,122.4L522,124.5L522.1,125.3L523.7,126.7L525.1,133L526,136.2L526.2,137.8L525.9,140.7L526.1,142.3L525.8,144.3L526.1,146.6L525.1,148.1L526.8,150.7L526.9,152.2L527.9,154.3L529.2,153.6L531.4,155.3L532.6,157.6L523.5,164.5L515.6,171.8L511.8,173.4L508.7,173.8L508.7,171.4L507.4,170.8L505.7,169.8L505,168L495.8,160L486.7,152.1L476.7,143.4Z"},{"code":"AO","name":"Angola","path":"M536.7,264L535.7,264.8L535.2,265.8L535.1,267.4L534.4,267.8L533.7,265L534.8,263.3L535.7,262.7L536.7,264ZM534.8,269L536,268.5L536.8,268.6L537.8,268.1L546.1,268.1L546.8,271L547.5,273.3L548.2,274.5L549.2,276.5L551.1,276.2L552,275.6L553.6,276.2L554,275.2L554.8,273L556.5,272.9L556.7,272.2L558.1,272.2L557.8,273.6L561.3,273.5L561.3,275.9L561.8,277.4L561.4,279.7L561.5,282L562.4,283.4L562.2,287.9L562.9,287.5L564.1,287.6L565.8,287.1L567.1,287.3L567.4,288.5L567,290.3L567.4,292.1L567,293.5L567.2,294.8L561.3,294.7L560.8,306.7L562.5,309.7L564.3,312L559.1,313.5L552.4,313L550.6,311.2L539.3,311.4L538.9,311.7L537.3,310L535.5,309.9L533.8,310.5L532.5,311.2L532.3,308.9L532.7,305.6L533.8,302.2L533.9,300.6L534.9,297.2L535.6,295.6L537.3,293.2L538.2,291.5L538.5,288.7L538.4,286.6L537.6,285.2L536.9,282.9L536.2,280.6L536.4,279.8L537.3,278.3L536.5,274.7L535.9,272.1L534.5,269.7L534.8,269Z"},{"code":"AR","name":"Argentinien","path":"M343.2,430.7L344.7,432L346.9,434.2L350.6,435.8L354.1,436.5L353.8,437.9L351.7,438.1L350.1,437.1L348.7,437L346.3,437L343.2,430.7ZM347.6,358.1L347.5,361L347.5,364.6L348.3,368L347.9,368.8L348.2,371L348.5,372.8L352.4,375.8L352.6,378.1L354.6,379.6L354.9,381.2L353.5,385.5L350.2,387.3L345.3,388L342.5,387.7L343.6,389.7L343.8,392.1L344.7,393.8L343.6,395L341.2,395.4L338.4,394.2L337.7,395.1L339.1,398.3L341.1,399.3L342.1,398.3L343.4,399.9L341.5,400.9L340.2,402.9L340.9,406.1L341,407.8L338.7,407.8L337.4,409.4L337.6,411.8L340.8,414L343.4,414.6L343.6,417.4L341.5,419.1L341.5,422.6L339.9,423.8L339.5,425.2L341.7,428.2L344,429.9L342.9,429.7L340.6,429.3L334.9,428.9L333.1,427.2L332.1,425L330.6,425.2L329.3,424.1L327.6,421L328.8,419.6L328.7,417.7L327.8,416.2L327.9,413.6L327.1,409.5L326.1,407.6L326.9,407L326.2,405.8L324.8,405.2L325.1,403.9L323.6,402.6L321.6,398.9L322.4,398.3L320.5,394.3L319.9,390.9L319.6,388L320.7,386.8L318.9,383.5L318,380.4L319.2,378.2L318.4,375.4L318.9,372L318,368.8L317.2,368.2L314.4,362.2L315.2,358.6L314.1,355.1L314.3,351.9L315.3,348.6L316.7,346.3L315.7,344.9L316,343.8L314.7,337.7L317.3,336L317.6,332.2L317.1,331.3L318.9,328L322.6,328.8L324.6,331.5L325.2,328.5L328.3,328.7L328.9,329.5L334.8,335.4L337.2,336L340.9,338.7L343.9,340.1L344.6,341.7L342.9,347.1L345.7,348.1L348.8,348.7L350.9,348.1L352.8,345.3L352.8,342.2L354,341.5L355.7,343.6L356.1,346.4L354.1,348.4L352.6,349.9L350.2,353.3L347.6,358.1Z"},{"code":"AM","name":"Armenien","path":"M617.6,104L616.7,104.1L615.2,102.2L615.1,101.7L614,101.7L613.1,100.8L612.6,100.9L611.4,99.9L609.4,99.1L609.3,97.5L608.6,96.3L611.9,95.8L612.6,96.7L613.7,97.3L613.4,98.1L615,99.2L614.5,100.3L615.8,101.2L617,101.7L617.6,104Z"},{"code":"AZ","name":"Aserbaidschan","path":"M615,93.8L615.8,94L617.9,95.9L619.1,96.2L619.3,95.3L620.5,94L622.2,95.7L624,98L625.2,98.2L626.2,99.1L624.2,99.3L624.4,101.9L624.2,103.1L623.5,103.9L623.9,105.5L623.3,105.7L621.4,103.9L621.9,102.3L620.9,101.3L620,101.6L617.6,104L617,101.7L615.8,101.2L614.5,100.3L615,99.2L613.4,98.1L613.7,97.3L612.6,96.7L611.9,95.8L612.4,95.3L614.5,96.2L615.9,96.4L616.1,96.1L614.5,94.3L615,93.8ZM616.7Line truncated
|
{"width":1000.0,"height":439.1,"countries":[{"code":"AF","name":"Afghanistan","path":"M669.6,108.7L671,108.7L673.1,109.4L674,109.9L675.5,108.8L676.6,109.4L677,107.9L678.5,108L678.7,107.5L678.6,106.1L679.3,104.9L680.9,105.7L681,106.7L681.8,106.9L682.4,109.7L683.8,110.8L684.5,110.1L685.5,109.8L686.6,108.3L688.4,108.5L691.1,108.5L691.8,109.5L690.5,109.9L689.4,110.5L686.6,110.9L684,111.6L683,113.1L684,114.5L684.8,116.2L683.9,117.6L684.4,119L684.1,120.2L681.6,120.1L683.2,122.4L681.8,123.3L681.2,125.4L681.9,127.5L681.1,128.4L680.1,128.1L678.2,128.6L678.1,129.5L676.2,129.5L675.2,131.5L675.8,134.5L672.6,136L670.7,135.7L670.4,136.5L668.7,136L666.1,136.5L661.3,134.7L663,131.5L662.3,129.3L660.2,128.7L659.5,126.5L658,123.7L658.7,121.8L657.4,121.3L657.6,118.8L657.5,114.5L660.5,115.8L662.3,115.4L662.5,113.8L664.4,113.3L665.5,112.3L665.3,109.6L667.2,108.9L667.3,107.7L668.8,108.6L669.6,108.7Z"},{"code":"AL","name":"Albanien","path":"M552.5,97.2L552.5,98L551.7,98.5L551.7,99.6L550.7,101.2L550.2,100.9L550.1,100.2L548.6,99.1L548.2,97.5L548.2,95.3L548.5,94.3L548,93.8L547.8,92.8L548.7,91.2L548.9,91.8L549.5,91.5L550.1,92.4L550.8,92.7L551,93.9L550.8,95L551.3,96.4L552.5,97.2Z"},{"code":"DZ","name":"Algerien","path":"M476.7,143.4L476.8,142.7L476.8,142.5L476.9,138.2L481.3,135.6L483.9,135.1L486.1,134.1L487.2,132.4L490.3,131L490.4,128.4L491.9,128.1L493.1,126.8L496.6,126.2L497.1,124.8L496.4,124.1L495.5,120.4L495.4,118.4L494.4,116.2L496.9,114.3L499.7,113.7L501.3,112.3L503.8,111.3L508.1,110.7L512.3,110.4L513.6,110.9L516,109.6L518.7,109.5L519.8,110.3L521.5,110.1L521.1,111.9L521.6,115.1L521.1,117.9L519.5,119.8L519.8,122.4L522,124.5L522.1,125.3L523.7,126.7L525.1,133L526,136.2L526.2,137.8L525.9,140.7L526.1,142.3L525.8,144.3L526.1,146.6L525.1,148.1L526.8,150.7L526.9,152.2L527.9,154.3L529.2,153.6L531.4,155.3L532.6,157.6L523.5,164.5L515.6,171.8L511.8,173.4L508.7,173.8L508.7,171.4L507.4,170.8L505.7,169.8L505,168L495.8,160L486.7,152.1L476.7,143.4Z"},{"code":"AO","name":"Angola","path":"M536.7,264L535.7,264.8L535.2,265.8L535.1,267.4L534.4,267.8L533.7,265L534.8,263.3L535.7,262.7L536.7,264ZM534.8,269L536,268.5L536.8,268.6L537.8,268.1L546.1,268.1L546.8,271L547.5,273.3L548.2,274.5L549.2,276.5L551.1,276.2L552,275.6L553.6,276.2L554,275.2L554.8,273L556.5,272.9L556.7,272.2L558.1,272.2L557.8,273.6L561.3,273.5L561.3,275.9L561.8,277.4L561.4,279.7L561.5,282L562.4,283.4L562.2,287.9L562.9,287.5L564.1,287.6L565.8,287.1L567.1,287.3L567.4,288.5L567,290.3L567.4,292.1L567,293.5L567.2,294.8L561.3,294.7L560.8,306.7L562.5,309.7L564.3,312L559.1,313.5L552.4,313L550.6,311.2L539.3,311.4L538.9,311.7L537.3,310L535.5,309.9L533.8,310.5L532.5,311.2L532.3,308.9L532.7,305.6L533.8,302.2L533.9,300.6L534.9,297.2L535.6,295.6L537.3,293.2L538.2,291.5L538.5,288.7L538.4,286.6L537.6,285.2L536.9,282.9L536.2,280.6L536.4,279.8L537.3,278.3L536.5,274.7L535.9,272.1L534.5,269.7L534.8,269Z"},{"code":"AR","name":"Argentinien","path":"M343.2,430.7L344.7,432L346.9,434.2L350.6,435.8L354.1,436.5L353.8,437.9L351.7,438.1L350.1,437.1L348.7,437L346.3,437L343.2,430.7ZM347.6,358.1L347.5,361L347.5,364.6L348.3,368L347.9,368.8L348.2,371L348.5,372.8L352.4,375.8L352.6,378.1L354.6,379.6L354.9,381.2L353.5,385.5L350.2,387.3L345.3,388L342.5,387.7L343.6,389.7L343.8,392.1L344.7,393.8L343.6,395L341.2,395.4L338.4,394.2L337.7,395.1L339.1,398.3L341.1,399.3L342.1,398.3L343.4,399.9L341.5,400.9L340.2,402.9L340.9,406.1L341,407.8L338.7,407.8L337.4,409.4L337.6,411.8L340.8,414L343.4,414.6L343.6,417.4L341.5,419.1L341.5,422.6L339.9,423.8L339.5,425.2L341.7,428.2L344,429.9L342.9,429.7L340.6,429.3L334.9,428.9L333.1,427.2L332.1,425L330.6,425.2L329.3,424.1L327.6,421L328.8,419.6L328.7,417.7L327.8,416.2L327.9,413.6L327.1,409.5L326.1,407.6L326.9,407L326.2,405.8L324.8,405.2L325.1,403.9L323.6,402.6L321.6,398.9L322.4,398.3L320.5,394.3L319.9,390.9L319.6,388L320.7,386.8L318.9,383.5L318,380.4L319.2,378.2L318.4,375.4L318.9,372L318,368.8L317.2,368.2L314.4,362.2L315.2,358.6L314.1,355.1L314.3,351.9L315.3,348.6L316.7,346.3L315.7,344.9L316,343.8L314.7,337.7L317.3,336L317.6,332.2L317.1,331.3L318.9,328L322.6,328.8L324.6,331.5L325.2,328.5L328.3,328.7L328.9,329.5L334.8,335.4L337.2,336L340.9,338.7L343.9,340.1L344.6,341.7L342.9,347.1L345.7,348.1L348.8,348.7L350.9,348.1L352.8,345.3L352.8,342.2L354,341.5L355.7,343.6L356.1,346.4L354.1,348.4L352.6,349.9L350.2,353.3L347.6,358.1Z"},{"code":"AM","name":"Armenien","path":"M617.6,104L616.7,104.1L615.2,102.2L615.1,101.7L614,101.7L613.1,100.8L612.6,100.9L611.4,99.9L609.4,99.1L609.3,97.5L608.6,96.3L611.9,95.8L612.6,96.7L613.7,97.3L613.4,98.1L615,99.2L614.5,100.3L615.8,101.2L617,101.7L617.6,104Z"},{"code":"AZ","name":"Aserbaidschan","path":"M615,93.8L615.8,94L617.9,95.9L619.1,96.2L619.3,95.3L620.5,94L622.2,95.7L624,98L625.2,98.2L626.2,99.1L624.2,99.3L624.4,101.9L624.2,103.1L623.5,103.9L623.9,105.5L623.3,105.7L621.4,103.9L621.9,102.3L620.9,101.3L620,101.6L617.6,104L617,101.7L615.8,101.2L614.5,100.3L615,99.2L613.4,98.1L613.7,97.3L612.6,96.7L611.9,95.8L612.4,95.3L614.5,96.2L615.9,96.4L616.1,96.1L614.5,94.3L615,93.8ZM616.7Line truncated
|
||||||
@@ -3,35 +3,34 @@
|
|||||||
@attribute [AllowAnonymous]
|
@attribute [AllowAnonymous]
|
||||||
@using Flypaper.Web.Auth
|
@using Flypaper.Web.Auth
|
||||||
@inject AdminAuthenticator Admin
|
@inject AdminAuthenticator Admin
|
||||||
|
@inject NavigationManager Navigation
|
||||||
|
|
||||||
<PageTitle>Flypaper · Anmelden</PageTitle>
|
<PageTitle>Flypaper · Anmelden</PageTitle>
|
||||||
|
|
||||||
<h1 class="login-title">Flypaper</h1>
|
<h1 class="login-title">Flypaper</h1>
|
||||||
|
|
||||||
@if (!Admin.IsConfigured)
|
<form method="post" action="/auth/login" class="card form">
|
||||||
{
|
<AntiforgeryToken />
|
||||||
<div class="banner bad">
|
<input type="hidden" name="returnUrl" value="@ReturnUrl" />
|
||||||
<strong>Zugang gesperrt.</strong>
|
<label for="password">Passwort</label>
|
||||||
Es ist kein Admin-Passwort gesetzt. Setze die Umgebungsvariable <code>Flypaper__Admin__Password</code> und starte den Container neu.
|
<input id="password" name="password" type="password" autocomplete="current-password" autofocus required />
|
||||||
</div>
|
@if (Error is not null)
|
||||||
}
|
{
|
||||||
else
|
<p class="error">Passwort falsch.</p>
|
||||||
{
|
}
|
||||||
<form method="post" action="/auth/login" class="card form">
|
<button type="submit">Anmelden</button>
|
||||||
<AntiforgeryToken />
|
</form>
|
||||||
<input type="hidden" name="returnUrl" value="@ReturnUrl" />
|
|
||||||
<label for="password">Passwort</label>
|
|
||||||
<input id="password" name="password" type="password" autocomplete="current-password" autofocus required />
|
|
||||||
@if (Error is not null)
|
|
||||||
{
|
|
||||||
<p class="error">Passwort falsch.</p>
|
|
||||||
}
|
|
||||||
<button type="submit">Anmelden</button>
|
|
||||||
</form>
|
|
||||||
}
|
|
||||||
|
|
||||||
@code {
|
@code {
|
||||||
[SupplyParameterFromQuery(Name = "error")] private string? Error { get; set; }
|
[SupplyParameterFromQuery(Name = "error")] private string? Error { get; set; }
|
||||||
|
|
||||||
[SupplyParameterFromQuery(Name = "returnUrl")] private string? ReturnUrl { get; set; }
|
[SupplyParameterFromQuery(Name = "returnUrl")] private string? ReturnUrl { get; set; }
|
||||||
|
|
||||||
|
protected override async Task OnInitializedAsync()
|
||||||
|
{
|
||||||
|
if (!await Admin.IsConfiguredAsync())
|
||||||
|
{
|
||||||
|
Navigation.NavigateTo("/setup");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
namespace Flypaper.Web.Components.Pages.Settings;
|
||||||
|
|
||||||
|
public sealed class HoldMethodModel
|
||||||
|
{
|
||||||
|
public string? Content { get; set; }
|
||||||
|
|
||||||
|
public string? MinDelayMs { get; set; }
|
||||||
|
|
||||||
|
public string? MaxDelayMs { get; set; }
|
||||||
|
|
||||||
|
public string? MinChunkSize { get; set; }
|
||||||
|
|
||||||
|
public string? MaxChunkSize { get; set; }
|
||||||
|
|
||||||
|
public string? MaxHoldDuration { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
@using System.Globalization
|
||||||
|
@using Flypaper.Core
|
||||||
|
@using Flypaper.Core.Settings
|
||||||
|
@using Flypaper.Core.Strategies
|
||||||
|
@using Flypaper.Storage.Settings
|
||||||
|
@using Microsoft.Extensions.Options
|
||||||
|
@inject IOptionsMonitor<DripOptions> Drip
|
||||||
|
@inject IOptionsMonitor<FlypaperOptions> Core
|
||||||
|
@inject RuntimeSettingsStore Store
|
||||||
|
@inject NavigationManager Navigation
|
||||||
|
|
||||||
|
<SettingsSection Id="hold-method" Title="Haltemethode" Description="Womit Flypaper gefangene Bots beschäftigt und wie langsam es antwortet. Änderungen gelten ab dem nächsten Fang." Badge="@(_hasOverrides ? "Angepasst" : null)">
|
||||||
|
@if (Saved == "saved")
|
||||||
|
{
|
||||||
|
<Notice>Gespeichert. Gilt ab dem nächsten Fang.</Notice>
|
||||||
|
}
|
||||||
|
else if (Saved == "reset")
|
||||||
|
{
|
||||||
|
<Notice>Haltemethode auf Standard zurückgesetzt.</Notice>
|
||||||
|
}
|
||||||
|
|
||||||
|
<EditForm Model="Model" FormName="hold-method" OnSubmit="SaveAsync" action="/settings#hold-method" id="hold-method-form">
|
||||||
|
<div class="s-body">
|
||||||
|
<fieldset class="choices">
|
||||||
|
<legend>Inhalt</legend>
|
||||||
|
<InputRadioGroup @bind-Value="Model!.Content">
|
||||||
|
<div class="choice-grid">
|
||||||
|
@foreach (var choice in Choices)
|
||||||
|
{
|
||||||
|
<label class="choice">
|
||||||
|
<InputRadio Value="@choice.Value" />
|
||||||
|
<span class="choice-body">
|
||||||
|
<strong>@choice.Title</strong>
|
||||||
|
<span>@choice.Text</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</InputRadioGroup>
|
||||||
|
@if (_errors.TryGetValue(nameof(HoldMethodModel.Content), out var contentError))
|
||||||
|
{
|
||||||
|
<p class="field-error">@contentError</p>
|
||||||
|
}
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<div class="fields">
|
||||||
|
<SettingsField Label="Pause min." For="drip-min-delay" Unit="ms" Hint="10 bis 30000" Errors="_errors" Key="@nameof(HoldMethodModel.MinDelayMs)">
|
||||||
|
<InputText id="drip-min-delay" @bind-Value="Model!.MinDelayMs" inputmode="numeric" data-bandwidth-input />
|
||||||
|
</SettingsField>
|
||||||
|
<SettingsField Label="Pause max." For="drip-max-delay" Unit="ms" Hint="Zufällig zwischen min. und max." Errors="_errors" Key="@nameof(HoldMethodModel.MaxDelayMs)">
|
||||||
|
<InputText id="drip-max-delay" @bind-Value="Model!.MaxDelayMs" inputmode="numeric" data-bandwidth-input />
|
||||||
|
</SettingsField>
|
||||||
|
<SettingsField Label="Paket min." For="drip-min-chunk" Unit="Bytes" Hint="1 bis 4096" Errors="_errors" Key="@nameof(HoldMethodModel.MinChunkSize)">
|
||||||
|
<InputText id="drip-min-chunk" @bind-Value="Model!.MinChunkSize" inputmode="numeric" data-bandwidth-input />
|
||||||
|
</SettingsField>
|
||||||
|
<SettingsField Label="Paket max." For="drip-max-chunk" Unit="Bytes" Hint="Zufällig zwischen min. und max." Errors="_errors" Key="@nameof(HoldMethodModel.MaxChunkSize)">
|
||||||
|
<InputText id="drip-max-chunk" @bind-Value="Model!.MaxChunkSize" inputmode="numeric" data-bandwidth-input />
|
||||||
|
</SettingsField>
|
||||||
|
<SettingsField Label="Maximale Haltedauer" For="hold" Hint="hh:mm:ss, höchstens 7 Tage" Errors="_errors" Key="@nameof(HoldMethodModel.MaxHoldDuration)">
|
||||||
|
<InputText id="hold" @bind-Value="Model!.MaxHoldDuration" />
|
||||||
|
</SettingsField>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="estimate">
|
||||||
|
<span class="estimate-value">Ø <strong id="drip-bandwidth">@Bandwidth</strong> Bytes/s</span>
|
||||||
|
<span class="muted">pro gefangener Verbindung, berechnet aus Pausen und Paketgrößen</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</EditForm>
|
||||||
|
|
||||||
|
<footer class="s-foot">
|
||||||
|
<EditForm Model="_resetModel" FormName="hold-method-reset" OnSubmit="ResetAsync" action="/settings#hold-method">
|
||||||
|
<button type="submit" class="ghost" disabled="@(!_hasOverrides)" onclick="return confirm('Haltemethode auf Standard zurücksetzen?')">Auf Standard zurücksetzen</button>
|
||||||
|
</EditForm>
|
||||||
|
<button type="submit" form="hold-method-form">Speichern</button>
|
||||||
|
</footer>
|
||||||
|
</SettingsSection>
|
||||||
|
|
||||||
|
<script src="@Assets["settings.js"]" defer></script>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private static readonly (string Value, string Title, string Text)[] Choices =
|
||||||
|
[
|
||||||
|
(nameof(DripContent.Html), "HTML-Fülltext", "Eine endlose Webseite mit Überschriften, Absätzen und Links. Wirkt auf Crawler am echtesten."),
|
||||||
|
(nameof(DripContent.Text), "Zufallstext", "Schlichter Text ohne Markup, ausgeliefert als text/plain."),
|
||||||
|
(nameof(DripContent.Alternating), "Wechselnd", "Pro Fang zufällig eine der beiden. Gut, um zu vergleichen, was Bots länger hält.")
|
||||||
|
];
|
||||||
|
|
||||||
|
private readonly object _resetModel = new();
|
||||||
|
private IReadOnlyDictionary<string, string> _errors = new Dictionary<string, string>();
|
||||||
|
private bool _hasOverrides;
|
||||||
|
|
||||||
|
[SupplyParameterFromForm(FormName = "hold-method")] private HoldMethodModel? Model { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "hold")] private string? Saved { get; set; }
|
||||||
|
|
||||||
|
private string Bandwidth
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
var ok = int.TryParse(Model?.MinDelayMs, out var minDelay) & int.TryParse(Model?.MaxDelayMs, out var maxDelay)
|
||||||
|
& int.TryParse(Model?.MinChunkSize, out var minChunk) & int.TryParse(Model?.MaxChunkSize, out var maxChunk);
|
||||||
|
if (!ok)
|
||||||
|
{
|
||||||
|
return "–";
|
||||||
|
}
|
||||||
|
|
||||||
|
var bytesPerSecond = HoldMethodSettings.AverageBytesPerSecond(
|
||||||
|
TimeSpan.FromMilliseconds(minDelay), TimeSpan.FromMilliseconds(maxDelay), minChunk, maxChunk);
|
||||||
|
return bytesPerSecond.ToString(bytesPerSecond < 10 ? "0.0" : "N0", Formatting.German);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task OnInitializedAsync()
|
||||||
|
{
|
||||||
|
Model ??= CurrentValues();
|
||||||
|
_hasOverrides = await Store.HasOverridesAsync(SettingKeys.HoldMethod.ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SaveAsync()
|
||||||
|
{
|
||||||
|
var result = RuntimeSettingsParser.ParseHoldMethod(new HoldMethodInput(
|
||||||
|
Model!.Content,
|
||||||
|
Model.MinDelayMs,
|
||||||
|
Model.MaxDelayMs,
|
||||||
|
Model.MinChunkSize,
|
||||||
|
Model.MaxChunkSize,
|
||||||
|
Model.MaxHoldDuration));
|
||||||
|
|
||||||
|
if (result.Settings is null)
|
||||||
|
{
|
||||||
|
_errors = result.Errors;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await Store.SaveAsync(result.Settings);
|
||||||
|
Navigation.NavigateTo("/settings?hold=saved#hold-method");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetAsync()
|
||||||
|
{
|
||||||
|
await Store.ResetAsync(SettingKeys.HoldMethod.ToArray());
|
||||||
|
Navigation.NavigateTo("/settings?hold=reset#hold-method");
|
||||||
|
}
|
||||||
|
|
||||||
|
private HoldMethodModel CurrentValues()
|
||||||
|
{
|
||||||
|
var drip = Drip.CurrentValue;
|
||||||
|
return new HoldMethodModel
|
||||||
|
{
|
||||||
|
Content = drip.Content.ToString(),
|
||||||
|
MinDelayMs = ((int)drip.MinDelay.TotalMilliseconds).ToString(CultureInfo.InvariantCulture),
|
||||||
|
MaxDelayMs = ((int)drip.MaxDelay.TotalMilliseconds).ToString(CultureInfo.InvariantCulture),
|
||||||
|
MinChunkSize = drip.MinChunkSize.ToString(CultureInfo.InvariantCulture),
|
||||||
|
MaxChunkSize = drip.MaxChunkSize.ToString(CultureInfo.InvariantCulture),
|
||||||
|
MaxHoldDuration = Core.CurrentValue.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
@using Flypaper.Storage.Entities
|
||||||
|
@using Flypaper.Storage.Settings
|
||||||
|
@using Flypaper.Web.Mcp
|
||||||
|
@inject McpTokenService Tokens
|
||||||
|
@inject McpTokenStore Store
|
||||||
|
@inject NavigationManager Navigation
|
||||||
|
|
||||||
|
<SettingsSection Id="mcp" Title="MCP-Zugriff" Description="KI-Assistenten wie Claude lesen die Fänge über das Model Context Protocol. Nur lesend und nur im LAN.">
|
||||||
|
@if (Revoked == "revoked")
|
||||||
|
{
|
||||||
|
<Notice>Token widerrufen.</Notice>
|
||||||
|
}
|
||||||
|
|
||||||
|
@if (_newToken is not null)
|
||||||
|
{
|
||||||
|
<Notice>
|
||||||
|
<strong>Token für „@_newTokenName“ erstellt.</strong> Jetzt kopieren, er wird nicht noch einmal angezeigt.
|
||||||
|
<code class="token">@_newToken</code>
|
||||||
|
</Notice>
|
||||||
|
}
|
||||||
|
|
||||||
|
<div class="s-body">
|
||||||
|
<dl class="kv">
|
||||||
|
<div><dt>Endpunkt</dt><dd class="mono">@Endpoint</dd></div>
|
||||||
|
<div><dt>Header</dt><dd class="mono">Authorization: Bearer <Token></dd></div>
|
||||||
|
@if (Tokens.UsesEnvironmentToken)
|
||||||
|
{
|
||||||
|
<div><dt>Fester Token</dt><dd>per Umgebungsvariable <code>Flypaper__Mcp__Token</code></dd></div>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
|
||||||
|
@if (_tokens.Count > 0)
|
||||||
|
{
|
||||||
|
<table class="s-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Name</th>
|
||||||
|
<th>Erstellt</th>
|
||||||
|
<th>Zuletzt genutzt</th>
|
||||||
|
<th></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var token in _tokens)
|
||||||
|
{
|
||||||
|
<tr>
|
||||||
|
<td>@token.Name</td>
|
||||||
|
<td class="nowrap">@token.CreatedAt.ToLocalTime().ToString("dd.MM.yyyy HH:mm")</td>
|
||||||
|
<td class="nowrap">@(token.LastUsedAt?.ToLocalTime().ToString("dd.MM.yyyy HH:mm") ?? "nie")</td>
|
||||||
|
<td class="num">
|
||||||
|
<form method="post" action="/mcp-tokens/@token.Id/revoke" onsubmit="return confirm('Token „@token.Name“ widerrufen?')">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<button type="submit" class="ghost danger-text">Widerrufen</button>
|
||||||
|
</form>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="empty">Noch keine Tokens.</p>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<EditForm Model="Model" FormName="mcp-create" OnSubmit="CreateAsync" action="/settings#mcp" class="s-foot">
|
||||||
|
<div class="inline-field">
|
||||||
|
<InputText id="mcp-token-name" @bind-Value="Model!.Name" autocomplete="off" maxlength="100" placeholder="Name, z. B. Claude Code" aria-label="Name des neuen Tokens" />
|
||||||
|
@if (_errors.TryGetValue(nameof(McpTokenModel.Name), out var nameError))
|
||||||
|
{
|
||||||
|
<span class="field-error">@nameError</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<button type="submit">Token erzeugen</button>
|
||||||
|
</EditForm>
|
||||||
|
</SettingsSection>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private IReadOnlyList<McpTokenEntity> _tokens = [];
|
||||||
|
private readonly Dictionary<string, string> _errors = [];
|
||||||
|
private string? _newToken;
|
||||||
|
private string? _newTokenName;
|
||||||
|
|
||||||
|
[SupplyParameterFromForm(FormName = "mcp-create")] private McpTokenModel? Model { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "mcp")] private string? Revoked { get; set; }
|
||||||
|
|
||||||
|
private string Endpoint => Navigation.BaseUri.TrimEnd('/') + McpExtensions.Path;
|
||||||
|
|
||||||
|
protected override async Task OnInitializedAsync()
|
||||||
|
{
|
||||||
|
Model ??= new McpTokenModel();
|
||||||
|
_tokens = await Store.ListAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task CreateAsync()
|
||||||
|
{
|
||||||
|
var name = Model!.Name?.Trim();
|
||||||
|
if (string.IsNullOrEmpty(name) || name.Length > 100)
|
||||||
|
{
|
||||||
|
_errors[nameof(McpTokenModel.Name)] = "Bitte einen Namen mit höchstens 100 Zeichen angeben.";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_newToken = await Tokens.CreateAsync(name);
|
||||||
|
_newTokenName = name;
|
||||||
|
Model.Name = null;
|
||||||
|
_tokens = await Store.ListAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace Flypaper.Web.Components.Pages.Settings;
|
||||||
|
|
||||||
|
public sealed class McpTokenModel
|
||||||
|
{
|
||||||
|
public string? Name { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<div class="notice @Kind" role="status">@ChildContent</div>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter] public string Kind { get; set; } = "ok";
|
||||||
|
|
||||||
|
[Parameter] public RenderFragment? ChildContent { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
namespace Flypaper.Web.Components.Pages.Settings;
|
||||||
|
|
||||||
|
public sealed class PasswordModel
|
||||||
|
{
|
||||||
|
public string? Current { get; set; }
|
||||||
|
|
||||||
|
public string? New { get; set; }
|
||||||
|
|
||||||
|
public string? Confirmation { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
@using Flypaper.Web.Auth
|
||||||
|
@inject AdminAuthenticator Admin
|
||||||
|
@inject NavigationManager Navigation
|
||||||
|
|
||||||
|
<SettingsSection Id="password" Title="Admin-Passwort" Description="Das Passwort für dieses Dashboard. Gespeichert wird nur ein gesalzener Hash.">
|
||||||
|
@if (Changed == "changed")
|
||||||
|
{
|
||||||
|
<Notice>Passwort geändert.</Notice>
|
||||||
|
}
|
||||||
|
|
||||||
|
<EditForm Model="Model" FormName="password" OnSubmit="ChangeAsync" action="/settings#password" id="password-form">
|
||||||
|
<div class="s-body">
|
||||||
|
<div class="fields">
|
||||||
|
<SettingsField Label="Aktuelles Passwort" For="current-password" Errors="_errors" Key="@nameof(PasswordModel.Current)">
|
||||||
|
<InputText id="current-password" type="password" autocomplete="current-password" @bind-Value="Model!.Current" />
|
||||||
|
</SettingsField>
|
||||||
|
<SettingsField Label="Neues Passwort" For="new-password" Hint="@($"Mindestens {AdminAuthenticator.MinimumPasswordLength} Zeichen")" Errors="_errors" Key="@nameof(PasswordModel.New)">
|
||||||
|
<InputText id="new-password" type="password" autocomplete="new-password" @bind-Value="Model!.New" />
|
||||||
|
</SettingsField>
|
||||||
|
<SettingsField Label="Neues Passwort wiederholen" For="confirm-password">
|
||||||
|
<InputText id="confirm-password" type="password" autocomplete="new-password" @bind-Value="Model!.Confirmation" />
|
||||||
|
</SettingsField>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</EditForm>
|
||||||
|
<footer class="s-foot">
|
||||||
|
<button type="submit" form="password-form">Passwort ändern</button>
|
||||||
|
</footer>
|
||||||
|
</SettingsSection>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private readonly Dictionary<string, string> _errors = [];
|
||||||
|
|
||||||
|
[SupplyParameterFromForm(FormName = "password")] private PasswordModel? Model { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "password")] private string? Changed { get; set; }
|
||||||
|
|
||||||
|
protected override void OnInitialized() => Model ??= new PasswordModel();
|
||||||
|
|
||||||
|
private async Task ChangeAsync()
|
||||||
|
{
|
||||||
|
if (AdminAuthenticator.ValidateNewPassword(Model!.New, Model.Confirmation) is { } error)
|
||||||
|
{
|
||||||
|
_errors[nameof(PasswordModel.New)] = error;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!await Admin.TryChangePasswordAsync(Model.Current ?? "", Model.New!))
|
||||||
|
{
|
||||||
|
_errors[nameof(PasswordModel.Current)] = "Aktuelles Passwort falsch.";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Navigation.NavigateTo("/settings?password=changed#password");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
<div class="field@(Wide ? " wide" : "")">
|
||||||
|
<label for="@For">@Label</label>
|
||||||
|
<div class="field-control@(Unit is null ? "" : " has-unit")">
|
||||||
|
@ChildContent
|
||||||
|
@if (Unit is not null)
|
||||||
|
{
|
||||||
|
<span class="field-unit">@Unit</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
@if (Errors is not null && Key is not null && Errors.TryGetValue(Key, out var error))
|
||||||
|
{
|
||||||
|
<p class="field-error">@error</p>
|
||||||
|
}
|
||||||
|
else if (Hint is not null)
|
||||||
|
{
|
||||||
|
<p class="field-hint">@Hint</p>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter, EditorRequired] public required string Label { get; set; }
|
||||||
|
|
||||||
|
[Parameter, EditorRequired] public required string For { get; set; }
|
||||||
|
|
||||||
|
[Parameter] public string? Unit { get; set; }
|
||||||
|
|
||||||
|
[Parameter] public string? Hint { get; set; }
|
||||||
|
|
||||||
|
[Parameter] public IReadOnlyDictionary<string, string>? Errors { get; set; }
|
||||||
|
|
||||||
|
[Parameter] public string? Key { get; set; }
|
||||||
|
|
||||||
|
[Parameter] public bool Wide { get; set; }
|
||||||
|
|
||||||
|
[Parameter] public RenderFragment? ChildContent { get; set; }
|
||||||
|
}
|
||||||
@@ -2,16 +2,10 @@ namespace Flypaper.Web.Components.Pages.Settings;
|
|||||||
|
|
||||||
public sealed class SettingsModel
|
public sealed class SettingsModel
|
||||||
{
|
{
|
||||||
public string? TrapPaths { get; set; }
|
|
||||||
|
|
||||||
public string? MaxConnections { get; set; }
|
public string? MaxConnections { get; set; }
|
||||||
|
|
||||||
public string? MaxConnectionsPerIp { get; set; }
|
public string? MaxConnectionsPerIp { get; set; }
|
||||||
|
|
||||||
public string? MaxHoldDuration { get; set; }
|
|
||||||
|
|
||||||
public string? ExtraKnownHosts { get; set; }
|
|
||||||
|
|
||||||
public string? RetentionDays { get; set; }
|
public string? RetentionDays { get; set; }
|
||||||
|
|
||||||
public bool IgnorePrivateNetworks { get; set; }
|
public bool IgnorePrivateNetworks { get; set; }
|
||||||
|
|||||||
@@ -9,103 +9,112 @@
|
|||||||
@using Microsoft.Data.Sqlite
|
@using Microsoft.Data.Sqlite
|
||||||
@using Microsoft.Extensions.Options
|
@using Microsoft.Extensions.Options
|
||||||
@inject IOptionsMonitor<FlypaperOptions> Core
|
@inject IOptionsMonitor<FlypaperOptions> Core
|
||||||
@inject IOptionsMonitor<HttpTrapOptions> Http
|
|
||||||
@inject IOptionsMonitor<RetentionOptions> Retention
|
@inject IOptionsMonitor<RetentionOptions> Retention
|
||||||
@inject IConfiguration Configuration
|
@inject IConfiguration Configuration
|
||||||
@inject RuntimeSettingsStore Store
|
@inject RuntimeSettingsStore Store
|
||||||
@inject AdminAuthenticator Admin
|
@inject AdminAuthenticator Admin
|
||||||
|
@inject IOptions<PortOptions> Ports
|
||||||
@inject NavigationManager Navigation
|
@inject NavigationManager Navigation
|
||||||
|
|
||||||
<PageTitle>Flypaper · Einstellungen</PageTitle>
|
<PageTitle>Flypaper · Einstellungen</PageTitle>
|
||||||
|
|
||||||
<header class="top">
|
<div class="settings">
|
||||||
<h1>Einstellungen</h1>
|
<header class="page-head">
|
||||||
@if (_hasOverrides)
|
<h1>Einstellungen</h1>
|
||||||
{
|
<p>Änderungen gelten sofort, ohne Neustart. Werte aus Umgebungsvariablen dienen als Standard.</p>
|
||||||
<span class="badge">Überschrieben</span>
|
</header>
|
||||||
}
|
|
||||||
</header>
|
|
||||||
|
|
||||||
@if (Saved == "1")
|
<div class="settings-layout">
|
||||||
{
|
<nav class="settings-nav" aria-label="Abschnitte">
|
||||||
<div class="banner ok">Gespeichert. Die Änderungen gelten sofort.</div>
|
<a href="settings#hold-method">Haltemethode</a>
|
||||||
}
|
<a href="settings#connections">Verbindungen & Speicherung</a>
|
||||||
else if (Saved == "reset")
|
<a href="settings#data">Daten</a>
|
||||||
{
|
@if (!Admin.UsesEnvironmentPassword)
|
||||||
<div class="banner ok">Auf Standard zurückgesetzt.</div>
|
{
|
||||||
}
|
<a href="settings#password">Admin-Passwort</a>
|
||||||
|
}
|
||||||
|
<a href="settings#mcp">MCP-Zugriff</a>
|
||||||
|
<a href="settings#system">System</a>
|
||||||
|
</nav>
|
||||||
|
|
||||||
<EditForm Model="Model" FormName="settings" OnSubmit="Save" action="/settings" class="card form">
|
<div class="settings-sections">
|
||||||
<h2>Anpassbar</h2>
|
<HoldMethodSection />
|
||||||
|
|
||||||
<label for="trap-paths">Fallenpfade <span class="muted">(einer pro Zeile, mit / am Anfang, * am Ende als Präfix)</span></label>
|
<SettingsSection Id="connections" Title="Verbindungen & Speicherung" Description="Wie viele Bots gleichzeitig festgehalten werden und wie lange Fänge gespeichert bleiben." Badge="@(_generalOverrides ? "Angepasst" : null)">
|
||||||
<InputTextArea id="trap-paths" @bind-Value="Model!.TrapPaths" rows="10" class="mono" />
|
@if (Saved == "1")
|
||||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.TrapPaths)" />
|
{
|
||||||
|
<Notice>Gespeichert. Gilt ab sofort.</Notice>
|
||||||
|
}
|
||||||
|
|
||||||
<label for="hosts">Zusätzliche bekannte Hosts <span class="muted">(einer pro Zeile, z. B. beispiel.de oder *.beispiel.de)</span></label>
|
<EditForm Model="Model" FormName="settings" OnSubmit="Save" action="/settings#connections" id="connections-form">
|
||||||
<InputTextArea id="hosts" @bind-Value="Model!.ExtraKnownHosts" rows="4" class="mono" />
|
<div class="s-body">
|
||||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.ExtraKnownHosts)" />
|
<div class="fields">
|
||||||
|
<SettingsField Label="Verbindungen gesamt" For="max" Hint="Höchstens so viele Bots gleichzeitig" Errors="_errors" Key="@nameof(SettingsModel.MaxConnections)">
|
||||||
|
<InputText id="max" @bind-Value="Model!.MaxConnections" inputmode="numeric" />
|
||||||
|
</SettingsField>
|
||||||
|
<SettingsField Label="Verbindungen pro IP" For="per-ip" Hint="Damit ein Scanner nicht alle Plätze belegt" Errors="_errors" Key="@nameof(SettingsModel.MaxConnectionsPerIp)">
|
||||||
|
<InputText id="per-ip" @bind-Value="Model!.MaxConnectionsPerIp" inputmode="numeric" />
|
||||||
|
</SettingsField>
|
||||||
|
<SettingsField Label="Fänge aufbewahren" For="retention" Unit="Tage" Hint="0 = unbegrenzt" Errors="_errors" Key="@nameof(SettingsModel.RetentionDays)">
|
||||||
|
<InputText id="retention" @bind-Value="Model!.RetentionDays" inputmode="numeric" />
|
||||||
|
</SettingsField>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="grid">
|
<label class="switch-row">
|
||||||
<div>
|
<InputCheckbox class="switch" @bind-Value="Model!.IgnorePrivateNetworks" />
|
||||||
<label for="hold">Maximale Haltedauer <span class="muted">(hh:mm:ss)</span></label>
|
<span>
|
||||||
<InputText id="hold" @bind-Value="Model!.MaxHoldDuration" class="mono" />
|
<strong>Fänge aus privaten Netzen nicht speichern</strong>
|
||||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.MaxHoldDuration)" />
|
<span class="muted">Die Falle greift trotzdem. Praktisch, damit eigene Tests die Statistik nicht verfälschen.</span>
|
||||||
</div>
|
</span>
|
||||||
<div>
|
</label>
|
||||||
<label for="max">Max. Verbindungen gesamt</label>
|
</div>
|
||||||
<InputText id="max" @bind-Value="Model!.MaxConnections" class="mono" />
|
</EditForm>
|
||||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.MaxConnections)" />
|
<footer class="s-foot">
|
||||||
</div>
|
<button type="submit" form="connections-form">Speichern</button>
|
||||||
<div>
|
</footer>
|
||||||
<label for="per-ip">Max. Verbindungen pro IP</label>
|
</SettingsSection>
|
||||||
<InputText id="per-ip" @bind-Value="Model!.MaxConnectionsPerIp" class="mono" />
|
|
||||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.MaxConnectionsPerIp)" />
|
<TrapDataSection />
|
||||||
</div>
|
|
||||||
<div>
|
@if (!Admin.UsesEnvironmentPassword)
|
||||||
<label for="retention">Fänge aufbewahren <span class="muted">(Tage, 0 = unbegrenzt)</span></label>
|
{
|
||||||
<InputText id="retention" @bind-Value="Model!.RetentionDays" class="mono" />
|
<PasswordSection />
|
||||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.RetentionDays)" />
|
}
|
||||||
|
|
||||||
|
<McpSection />
|
||||||
|
|
||||||
|
<SettingsSection Id="system" Title="System" Description="Werte aus Umgebungsvariablen. Sie gelten ab Containerstart und lassen sich hier nicht ändern.">
|
||||||
|
@if (Saved == "reset")
|
||||||
|
{
|
||||||
|
<Notice>Alle gespeicherten Einstellungen wurden zurückgesetzt.</Notice>
|
||||||
|
}
|
||||||
|
|
||||||
|
<div class="s-body">
|
||||||
|
<dl class="kv">
|
||||||
|
<div><dt>Version</dt><dd class="mono">@AppVersion.Current</dd></div>
|
||||||
|
<div><dt>Ports</dt><dd class="mono">Falle @Ports.Value.Trap · Dashboard @Ports.Value.Dashboard</dd></div>
|
||||||
|
<div><dt>Datenbank</dt><dd class="mono">@DatabasePath</dd></div>
|
||||||
|
<div><dt>Vertrauenswürdige Proxies</dt><dd class="mono">@TrustedProxies</dd></div>
|
||||||
|
<div><dt>Admin-Passwort</dt><dd>@(Admin.UsesEnvironmentPassword ? "per Umgebungsvariable" : "im Dashboard festgelegt")</dd></div>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<footer class="s-foot">
|
||||||
|
<span class="s-foot-text">Alle im Dashboard gespeicherten Einstellungen löschen. Danach gelten wieder die Standardwerte.</span>
|
||||||
|
<EditForm Model="_resetModel" FormName="reset" OnSubmit="Reset" action="/settings#system">
|
||||||
|
<button type="submit" class="secondary" disabled="@(!_hasOverrides)" onclick="return confirm('Alle gespeicherten Einstellungen zurücksetzen?')">Alles zurücksetzen</button>
|
||||||
|
</EditForm>
|
||||||
|
</footer>
|
||||||
|
</SettingsSection>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
<label class="check">
|
|
||||||
<InputCheckbox @bind-Value="Model!.IgnorePrivateNetworks" />
|
|
||||||
Fänge aus privaten Netzen nicht speichern <span class="muted">(die Falle greift trotzdem)</span>
|
|
||||||
</label>
|
|
||||||
|
|
||||||
<div class="actions">
|
|
||||||
<button type="submit">Speichern</button>
|
|
||||||
</div>
|
|
||||||
</EditForm>
|
|
||||||
|
|
||||||
<EditForm Model="_resetModel" FormName="reset" OnSubmit="Reset" action="/settings" class="card form">
|
|
||||||
<h2>Standard</h2>
|
|
||||||
<p class="muted">Löscht alle gespeicherten Änderungen. Danach gelten wieder die Werte aus Umgebungsvariablen und appsettings.</p>
|
|
||||||
<div class="actions">
|
|
||||||
<button type="submit" class="secondary" disabled="@(!_hasOverrides)" onclick="return confirm('Gespeicherte Einstellungen wirklich löschen?')">Auf Standard zurücksetzen</button>
|
|
||||||
</div>
|
|
||||||
</EditForm>
|
|
||||||
|
|
||||||
<TrapDataSection />
|
|
||||||
|
|
||||||
<section class="card">
|
|
||||||
<h2>Nur per Umgebungsvariable</h2>
|
|
||||||
<p class="muted">Gelten ab Containerstart und lassen sich hier nicht ändern.</p>
|
|
||||||
<table>
|
|
||||||
<tbody>
|
|
||||||
<tr><th>Datenbank</th><td class="mono">@DatabasePath</td></tr>
|
|
||||||
<tr><th>Bekannte Hosts</th><td class="mono">@Format(Configuration.GetSection("Flypaper:Http:KnownHosts").Get<string[]>())</td></tr>
|
|
||||||
<tr><th>Vertrauenswürdige Proxies</th><td class="mono">@Format(Configuration.GetSection("Flypaper:Http:TrustedProxies").Get<string[]>())</td></tr>
|
|
||||||
<tr><th>Admin-Passwort</th><td>@(Admin.IsConfigured ? "gesetzt" : "nicht gesetzt")</td></tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
@code {
|
@code {
|
||||||
private readonly object _resetModel = new();
|
private readonly object _resetModel = new();
|
||||||
private IReadOnlyDictionary<string, string> _errors = new Dictionary<string, string>();
|
private IReadOnlyDictionary<string, string> _errors = new Dictionary<string, string>();
|
||||||
private bool _hasOverrides;
|
private bool _hasOverrides;
|
||||||
|
private bool _generalOverrides;
|
||||||
|
|
||||||
[SupplyParameterFromForm(FormName = "settings")] private SettingsModel? Model { get; set; }
|
[SupplyParameterFromForm(FormName = "settings")] private SettingsModel? Model { get; set; }
|
||||||
|
|
||||||
@@ -118,16 +127,14 @@ else if (Saved == "reset")
|
|||||||
{
|
{
|
||||||
Model ??= CurrentValues();
|
Model ??= CurrentValues();
|
||||||
_hasOverrides = await Store.HasOverridesAsync();
|
_hasOverrides = await Store.HasOverridesAsync();
|
||||||
|
_generalOverrides = await Store.HasOverridesAsync(SettingKeys.General.ToArray());
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task Save()
|
private async Task Save()
|
||||||
{
|
{
|
||||||
var result = RuntimeSettingsParser.Parse(new RuntimeSettingsInput(
|
var result = RuntimeSettingsParser.Parse(new RuntimeSettingsInput(
|
||||||
Model!.TrapPaths,
|
Model!.MaxConnections,
|
||||||
Model.MaxConnections,
|
|
||||||
Model.MaxConnectionsPerIp,
|
Model.MaxConnectionsPerIp,
|
||||||
Model.MaxHoldDuration,
|
|
||||||
Model.ExtraKnownHosts,
|
|
||||||
Model.RetentionDays,
|
Model.RetentionDays,
|
||||||
Model.IgnorePrivateNetworks));
|
Model.IgnorePrivateNetworks));
|
||||||
|
|
||||||
@@ -138,24 +145,20 @@ else if (Saved == "reset")
|
|||||||
}
|
}
|
||||||
|
|
||||||
await Store.SaveAsync(result.Settings);
|
await Store.SaveAsync(result.Settings);
|
||||||
Navigation.NavigateTo("/settings?saved=1");
|
Navigation.NavigateTo("/settings?saved=1#connections");
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task Reset()
|
private async Task Reset()
|
||||||
{
|
{
|
||||||
await Store.ResetAsync();
|
await Store.ResetAsync();
|
||||||
Navigation.NavigateTo("/settings?saved=reset");
|
Navigation.NavigateTo("/settings?saved=reset#system");
|
||||||
}
|
}
|
||||||
|
|
||||||
private SettingsModel CurrentValues()
|
private SettingsModel CurrentValues()
|
||||||
{
|
{
|
||||||
var core = Core.CurrentValue;
|
var core = Core.CurrentValue;
|
||||||
var http = Http.CurrentValue;
|
|
||||||
return new SettingsModel
|
return new SettingsModel
|
||||||
{
|
{
|
||||||
TrapPaths = SettingsList.Join(http.TrapPaths),
|
|
||||||
ExtraKnownHosts = SettingsList.Join(SettingsList.Split(http.ExtraKnownHosts)),
|
|
||||||
MaxHoldDuration = core.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
|
|
||||||
MaxConnections = core.MaxConnections.ToString(CultureInfo.InvariantCulture),
|
MaxConnections = core.MaxConnections.ToString(CultureInfo.InvariantCulture),
|
||||||
MaxConnectionsPerIp = core.MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
|
MaxConnectionsPerIp = core.MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
|
||||||
RetentionDays = Retention.CurrentValue.Days.ToString(CultureInfo.InvariantCulture),
|
RetentionDays = Retention.CurrentValue.Days.ToString(CultureInfo.InvariantCulture),
|
||||||
@@ -163,5 +166,8 @@ else if (Saved == "reset")
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string Format(string[]? values) => values is { Length: > 0 } ? string.Join(", ", values) : "–";
|
private string TrustedProxies =>
|
||||||
|
Configuration.GetSection("Flypaper:Http:TrustedProxies").Get<string[]>()?.Where(p => !string.IsNullOrWhiteSpace(p)).ToArray() is { Length: > 0 } proxies
|
||||||
|
? string.Join(", ", proxies)
|
||||||
|
: "private Netze (Standard)";
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<section class="s-section@(Danger ? " danger" : "")" id="@Id">
|
||||||
|
<header class="s-head">
|
||||||
|
<h2>
|
||||||
|
@Title
|
||||||
|
@if (Badge is not null)
|
||||||
|
{
|
||||||
|
<span class="s-badge">@Badge</span>
|
||||||
|
}
|
||||||
|
</h2>
|
||||||
|
@if (Description is not null)
|
||||||
|
{
|
||||||
|
<p>@Description</p>
|
||||||
|
}
|
||||||
|
</header>
|
||||||
|
@ChildContent
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[Parameter, EditorRequired] public required string Id { get; set; }
|
||||||
|
|
||||||
|
[Parameter, EditorRequired] public required string Title { get; set; }
|
||||||
|
|
||||||
|
[Parameter] public string? Description { get; set; }
|
||||||
|
|
||||||
|
[Parameter] public string? Badge { get; set; }
|
||||||
|
|
||||||
|
[Parameter] public bool Danger { get; set; }
|
||||||
|
|
||||||
|
[Parameter] public RenderFragment? ChildContent { get; set; }
|
||||||
|
}
|
||||||
@@ -2,46 +2,57 @@
|
|||||||
@inject TrapDataMaintenance Maintenance
|
@inject TrapDataMaintenance Maintenance
|
||||||
@inject NavigationManager Navigation
|
@inject NavigationManager Navigation
|
||||||
|
|
||||||
<section class="card form">
|
<SettingsSection Id="data" Title="Daten" Description="Gespeicherte Fänge. Einstellungen und GeoIP-Dateien bleiben beim Löschen erhalten.">
|
||||||
<h2>Daten</h2>
|
|
||||||
|
|
||||||
@if (Deleted is { } deleted)
|
@if (Deleted is { } deleted)
|
||||||
{
|
{
|
||||||
<div class="banner ok">@deleted.ToString("N0") @(deleted == 1 ? "Fang" : "Fänge") gelöscht.</div>
|
<Notice>@Formatting.Number(deleted) @(deleted == 1 ? "Fang" : "Fänge") gelöscht.</Notice>
|
||||||
}
|
}
|
||||||
|
|
||||||
<table>
|
<div class="s-body">
|
||||||
<tbody>
|
<div class="stat-row">
|
||||||
<tr><th>Fänge</th><td>@_stats?.Count.ToString("N0")</td></tr>
|
<div class="stat"><span class="stat-label">Fänge</span><span class="stat-value">@((_stats is null ? null : Formatting.Number(_stats.Count)) ?? "–")</span></div>
|
||||||
<tr><th>Ältester Fang</th><td>@(_stats?.Oldest?.ToLocalTime().ToString("dd.MM.yyyy HH:mm") ?? "–")</td></tr>
|
<div class="stat"><span class="stat-label">Ältester Fang</span><span class="stat-value">@(_stats?.Oldest?.ToLocalTime().ToString("dd.MM.yyyy") ?? "–")</span></div>
|
||||||
<tr><th>Größe der Datenbank</th><td>@Formatting.Bytes(_stats?.DatabaseBytes)</td></tr>
|
<div class="stat"><span class="stat-label">Datenbank</span><span class="stat-value">@Formatting.Bytes(_stats?.DatabaseBytes)</span></div>
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
<p class="muted">Einstellungen und GeoIP-Dateien bleiben beim Löschen erhalten.</p>
|
|
||||||
|
|
||||||
<EditForm Model="DeletePrivate" FormName="delete-private" OnSubmit="DeletePrivateAsync" action="/settings" class="danger-zone">
|
|
||||||
<h3>Fänge aus privaten Netzen löschen</h3>
|
|
||||||
<p class="muted">Loopback, 10/8, 172.16/12, 192.168/16, Link-Local und ULA, zum Beispiel lokale Testaufrufe.</p>
|
|
||||||
<label class="check">
|
|
||||||
<InputCheckbox @bind-Value="DeletePrivate!.Confirmed" />
|
|
||||||
Ich bin sicher
|
|
||||||
</label>
|
|
||||||
<FieldError Errors="_errors" Field="@nameof(DeletePrivateModel.Confirmed)" />
|
|
||||||
<div class="actions">
|
|
||||||
<button type="submit" class="secondary">Private Fänge löschen</button>
|
|
||||||
</div>
|
</div>
|
||||||
</EditForm>
|
</div>
|
||||||
|
|
||||||
<EditForm Model="DeleteAll" FormName="delete-all" OnSubmit="DeleteAllAsync" action="/settings" class="danger-zone">
|
<div class="danger-box">
|
||||||
<h3>Alle Fänge löschen</h3>
|
<h3>Gefahrenzone</h3>
|
||||||
<label for="delete-all-confirmation">Zum Bestätigen <strong>LÖSCHEN</strong> eingeben</label>
|
|
||||||
<InputText id="delete-all-confirmation" @bind-Value="DeleteAll!.Confirmation" autocomplete="off" />
|
<EditForm Model="DeletePrivate" FormName="delete-private" OnSubmit="DeletePrivateAsync" action="/settings#data" class="action-row">
|
||||||
<FieldError Errors="_errors" Field="@nameof(DeleteAllModel.Confirmation)" />
|
<div class="action-text">
|
||||||
<div class="actions">
|
<strong>Fänge aus privaten Netzen löschen</strong>
|
||||||
<button type="submit" class="danger">Alle Fänge löschen</button>
|
<span class="muted">Loopback, 10/8, 172.16/12, 192.168/16, Link-Local und ULA, etwa eigene Testaufrufe.</span>
|
||||||
</div>
|
@if (_errors.TryGetValue(nameof(DeletePrivateModel.Confirmed), out var privateError))
|
||||||
</EditForm>
|
{
|
||||||
</section>
|
<span class="field-error">@privateError</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="action-controls">
|
||||||
|
<label class="inline-check">
|
||||||
|
<InputCheckbox @bind-Value="DeletePrivate!.Confirmed" />
|
||||||
|
Ich bin sicher
|
||||||
|
</label>
|
||||||
|
<button type="submit" class="secondary">Private löschen</button>
|
||||||
|
</div>
|
||||||
|
</EditForm>
|
||||||
|
|
||||||
|
<EditForm Model="DeleteAll" FormName="delete-all" OnSubmit="DeleteAllAsync" action="/settings#data" class="action-row">
|
||||||
|
<div class="action-text">
|
||||||
|
<strong>Alle Fänge löschen</strong>
|
||||||
|
<span class="muted">Zum Bestätigen <strong>LÖSCHEN</strong> eingeben. Lässt sich nicht rückgängig machen.</span>
|
||||||
|
@if (_errors.TryGetValue(nameof(DeleteAllModel.Confirmation), out var allError))
|
||||||
|
{
|
||||||
|
<span class="field-error">@allError</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="action-controls">
|
||||||
|
<InputText id="delete-all-confirmation" @bind-Value="DeleteAll!.Confirmation" autocomplete="off" placeholder="LÖSCHEN" aria-label="Bestätigung" />
|
||||||
|
<button type="submit" class="danger">Alle löschen</button>
|
||||||
|
</div>
|
||||||
|
</EditForm>
|
||||||
|
</div>
|
||||||
|
</SettingsSection>
|
||||||
|
|
||||||
@code {
|
@code {
|
||||||
private const string ConfirmationWord = "LÖSCHEN";
|
private const string ConfirmationWord = "LÖSCHEN";
|
||||||
@@ -91,6 +102,6 @@
|
|||||||
await Maintenance.VacuumAsync();
|
await Maintenance.VacuumAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
Navigation.NavigateTo($"/settings?deleted={deleted}");
|
Navigation.NavigateTo($"/settings?deleted={deleted}#data");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
@page "/setup"
|
||||||
|
@layout EmptyLayout
|
||||||
|
@attribute [AllowAnonymous]
|
||||||
|
@using Flypaper.Web.Auth
|
||||||
|
@inject AdminAuthenticator Admin
|
||||||
|
@inject NavigationManager Navigation
|
||||||
|
|
||||||
|
<PageTitle>Flypaper · Einrichten</PageTitle>
|
||||||
|
|
||||||
|
<h1 class="login-title">Flypaper einrichten</h1>
|
||||||
|
|
||||||
|
<form method="post" action="/auth/setup" class="card form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<p class="muted">Lege das Admin-Passwort für das Dashboard fest. Diese Seite ist nur erreichbar, solange noch kein Passwort existiert.</p>
|
||||||
|
<label for="password">Passwort <span class="muted">(mindestens @AdminAuthenticator.MinimumPasswordLength Zeichen)</span></label>
|
||||||
|
<input id="password" name="password" type="password" autocomplete="new-password" minlength="@AdminAuthenticator.MinimumPasswordLength" autofocus required />
|
||||||
|
<label for="confirmation">Passwort wiederholen</label>
|
||||||
|
<input id="confirmation" name="confirmation" type="password" autocomplete="new-password" required />
|
||||||
|
@if (Error is not null)
|
||||||
|
{
|
||||||
|
<p class="error">@Error</p>
|
||||||
|
}
|
||||||
|
<button type="submit">Passwort festlegen</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
[SupplyParameterFromQuery(Name = "error")] private string? Error { get; set; }
|
||||||
|
|
||||||
|
protected override async Task OnInitializedAsync()
|
||||||
|
{
|
||||||
|
if (await Admin.IsConfiguredAsync())
|
||||||
|
{
|
||||||
|
Navigation.NavigateTo("/login");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
namespace Flypaper.Web.Components.Shared;
|
||||||
|
|
||||||
|
public static class CountryNames
|
||||||
|
{
|
||||||
|
private static readonly Dictionary<string, string> ShortNames = new(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{
|
||||||
|
["BN"] = "Brunei",
|
||||||
|
["BO"] = "Bolivien",
|
||||||
|
["CD"] = "Kongo (Dem. Rep.)",
|
||||||
|
["CG"] = "Kongo",
|
||||||
|
["CI"] = "Elfenbeinküste",
|
||||||
|
["CN"] = "China",
|
||||||
|
["CY"] = "Zypern",
|
||||||
|
["CZ"] = "Tschechien",
|
||||||
|
["FM"] = "Mikronesien",
|
||||||
|
["GB"] = "Vereinigtes Königreich",
|
||||||
|
["HK"] = "Hongkong",
|
||||||
|
["IR"] = "Iran",
|
||||||
|
["KP"] = "Nordkorea",
|
||||||
|
["KR"] = "Südkorea",
|
||||||
|
["LA"] = "Laos",
|
||||||
|
["MD"] = "Moldau",
|
||||||
|
["MK"] = "Nordmazedonien",
|
||||||
|
["MO"] = "Macau",
|
||||||
|
["PS"] = "Palästina",
|
||||||
|
["RU"] = "Russland",
|
||||||
|
["SY"] = "Syrien",
|
||||||
|
["SZ"] = "Eswatini",
|
||||||
|
["TL"] = "Osttimor",
|
||||||
|
["TW"] = "Taiwan",
|
||||||
|
["TZ"] = "Tansania",
|
||||||
|
["US"] = "USA",
|
||||||
|
["VA"] = "Vatikanstadt",
|
||||||
|
["VE"] = "Venezuela",
|
||||||
|
["VN"] = "Vietnam"
|
||||||
|
};
|
||||||
|
|
||||||
|
public static string? Display(string? code, string? name) =>
|
||||||
|
code is not null && ShortNames.TryGetValue(code, out var shortName) ? shortName : name ?? code;
|
||||||
|
}
|
||||||
@@ -1,7 +1,13 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
|
||||||
namespace Flypaper.Web.Components.Shared;
|
namespace Flypaper.Web.Components.Shared;
|
||||||
|
|
||||||
public static class Formatting
|
public static class Formatting
|
||||||
{
|
{
|
||||||
|
public static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
|
||||||
|
|
||||||
|
public static string Number(long value) => value.ToString("N0", German);
|
||||||
|
|
||||||
public static string Duration(TimeSpan duration) => duration switch
|
public static string Duration(TimeSpan duration) => duration switch
|
||||||
{
|
{
|
||||||
{ TotalDays: >= 1 } => $"{(int)duration.TotalDays}\u00a0d {duration.Hours}\u00a0h",
|
{ TotalDays: >= 1 } => $"{(int)duration.TotalDays}\u00a0d {duration.Hours}\u00a0h",
|
||||||
@@ -24,5 +30,24 @@ public static class Formatting
|
|||||||
_ => $"{bytes} B"
|
_ => $"{bytes} B"
|
||||||
};
|
};
|
||||||
|
|
||||||
|
public static string? Target(string? target)
|
||||||
|
{
|
||||||
|
var space = target?.IndexOf(' ') ?? -1;
|
||||||
|
if (space < 0)
|
||||||
|
{
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
|
var hostAndPath = target![(space + 1)..];
|
||||||
|
if (hostAndPath.StartsWith('/'))
|
||||||
|
{
|
||||||
|
return $"{target[..space]} (ohne Host){hostAndPath}";
|
||||||
|
}
|
||||||
|
|
||||||
|
return hostAndPath == "_" || hostAndPath.StartsWith("_/", StringComparison.Ordinal)
|
||||||
|
? $"{target[..space]} (ohne Host){hostAndPath[1..]}"
|
||||||
|
: target;
|
||||||
|
}
|
||||||
|
|
||||||
public static string? Provider(long? asn, string? provider) => asn is null ? provider : $"AS{asn} {provider}".TrimEnd();
|
public static string? Provider(long? asn, string? provider) => asn is null ? provider : $"AS{asn} {provider}".TrimEnd();
|
||||||
}
|
}
|
||||||
@@ -9,10 +9,18 @@
|
|||||||
<EmbeddedResource Include="Components\Pages\Dashboard\world-map.json" LogicalName="Flypaper.Web.world-map.json" />
|
<EmbeddedResource Include="Components\Pages\Dashboard\world-map.json" LogicalName="Flypaper.Web.world-map.json" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="ModelContextProtocol.AspNetCore" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Flypaper.GeoIp\Flypaper.GeoIp.csproj" />
|
<ProjectReference Include="..\Flypaper.GeoIp\Flypaper.GeoIp.csproj" />
|
||||||
<ProjectReference Include="..\Flypaper.Http\Flypaper.Http.csproj" />
|
<ProjectReference Include="..\Flypaper.Http\Flypaper.Http.csproj" />
|
||||||
<ProjectReference Include="..\Flypaper.Storage\Flypaper.Storage.csproj" />
|
<ProjectReference Include="..\Flypaper.Storage\Flypaper.Storage.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<InternalsVisibleTo Include="Flypaper.Tests" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
using System.ComponentModel;
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Net;
|
||||||
|
using Flypaper.Core.Abstractions;
|
||||||
|
using Flypaper.Storage.Queries;
|
||||||
|
using Flypaper.Web.Components.Shared;
|
||||||
|
using ModelContextProtocol;
|
||||||
|
using ModelContextProtocol.Server;
|
||||||
|
|
||||||
|
namespace Flypaper.Web.Mcp;
|
||||||
|
|
||||||
|
[McpServerToolType]
|
||||||
|
public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor governor, TimeProvider timeProvider)
|
||||||
|
{
|
||||||
|
private const string PeriodDescription = "Time window ending now: a number with m (minutes), h (hours), d (days) or w (weeks), e.g. 1h, 24h, 7d; or all.";
|
||||||
|
|
||||||
|
[McpServerTool(Name = "get_stats", Title = "Trap statistics", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||||
|
[Description("Summary of the tarpit for a time window: number of catches and rejected connections, unique IPs, total and average hold time, traps active right now and the longest catch.")]
|
||||||
|
public async Task<StatsResult> GetStats(
|
||||||
|
[Description(PeriodDescription)] string period = "24h",
|
||||||
|
CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var since = Since(period);
|
||||||
|
var stats = await queries.GetStatsAsync(since, ct);
|
||||||
|
return new StatsResult(
|
||||||
|
Normalize(period),
|
||||||
|
since,
|
||||||
|
stats.Catches,
|
||||||
|
stats.Rejected,
|
||||||
|
stats.UniqueIps,
|
||||||
|
Round(stats.TotalHoldSeconds),
|
||||||
|
Round(stats.AverageHoldSeconds),
|
||||||
|
governor.ActiveConnections,
|
||||||
|
stats.Longest is null ? null : ToItem(stats.Longest));
|
||||||
|
}
|
||||||
|
|
||||||
|
[McpServerTool(Name = "list_catches", Title = "List catches", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||||
|
[Description("Trap events, newest first, optionally filtered. Includes rejected connections (outcome Rejected).")]
|
||||||
|
public async Task<CatchListResult> ListCatches(
|
||||||
|
[Description("Only events that started at or after this ISO 8601 time, e.g. 2026-11-15T08:00:00Z.")] string? since = null,
|
||||||
|
[Description("Only events that started before this ISO 8601 time.")] string? until = null,
|
||||||
|
[Description("Country as ISO 3166-1 alpha-2 code, e.g. CN or GB.")] string? country = null,
|
||||||
|
[Description("Network provider: an AS number such as AS4134, or part of the provider name.")] string? provider = null,
|
||||||
|
[Description("Exact client IP address.")] string? ip = null,
|
||||||
|
[Description("Case-insensitive text the request (method, host and path) must contain, e.g. .env.")] string? target_contains = null,
|
||||||
|
[Description("Maximum number of events, 1 to 500.")] int limit = 50,
|
||||||
|
CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var filter = new CatchFilter(
|
||||||
|
ParseTime(since, nameof(since)),
|
||||||
|
ParseTime(until, nameof(until)),
|
||||||
|
country,
|
||||||
|
provider,
|
||||||
|
ip is null ? null : ParseIp(ip),
|
||||||
|
target_contains,
|
||||||
|
limit);
|
||||||
|
var catches = (await queries.ListAsync(filter, ct)).Select(ToItem).ToList();
|
||||||
|
return new CatchListResult(catches.Count, catches);
|
||||||
|
}
|
||||||
|
|
||||||
|
[McpServerTool(Name = "top", Title = "Top values", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||||
|
[Description("Most frequent values among the catches of a time window, by number of catches. Rejected connections are not counted.")]
|
||||||
|
public async Task<TopResult> Top(
|
||||||
|
[Description("What to rank by: ips, countries, providers, targets or user_agents.")]
|
||||||
|
[AllowedValues("ips", "countries", "providers", "targets", "user_agents")]
|
||||||
|
string dimension,
|
||||||
|
[Description(PeriodDescription)] string period = "24h",
|
||||||
|
[Description("Number of entries, 1 to 500.")] int limit = 10,
|
||||||
|
CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var parsed = dimension.Trim().ToLowerInvariant() switch
|
||||||
|
{
|
||||||
|
"ips" => TopDimension.Ips,
|
||||||
|
"countries" => TopDimension.Countries,
|
||||||
|
"providers" => TopDimension.Providers,
|
||||||
|
"targets" => TopDimension.Targets,
|
||||||
|
"user_agents" => TopDimension.UserAgents,
|
||||||
|
_ => throw new McpException("dimension must be one of ips, countries, providers, targets, user_agents.")
|
||||||
|
};
|
||||||
|
|
||||||
|
var items = await queries.TopAsync(parsed, Since(period), limit, ct);
|
||||||
|
return new TopResult(
|
||||||
|
dimension.Trim().ToLowerInvariant(),
|
||||||
|
Normalize(period),
|
||||||
|
items.Select(i => new TopResultItem(
|
||||||
|
i.Key,
|
||||||
|
parsed == TopDimension.Countries ? CountryNames.Display(i.Key, i.Label) : i.Label,
|
||||||
|
i.Catches,
|
||||||
|
Round(i.TotalHoldSeconds))).ToList());
|
||||||
|
}
|
||||||
|
|
||||||
|
[McpServerTool(Name = "longest_catches", Title = "Longest catches", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||||
|
[Description("The catches that held a bot the longest within a time window, longest first.")]
|
||||||
|
public async Task<CatchListResult> LongestCatches(
|
||||||
|
[Description(PeriodDescription)] string period = "7d",
|
||||||
|
[Description("Number of catches, 1 to 500.")] int limit = 10,
|
||||||
|
CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var catches = (await queries.LongestAsync(Since(period), limit, ct)).Select(ToItem).ToList();
|
||||||
|
return new CatchListResult(catches.Count, catches);
|
||||||
|
}
|
||||||
|
|
||||||
|
[McpServerTool(Name = "lookup_ip", Title = "Look up an IP", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||||
|
[Description("Everything Flypaper has stored about one IP address: origin, network provider, totals, first and last seen, and its events (newest first, at most 500). Uses only local data.")]
|
||||||
|
public async Task<IpLookupResult> LookupIp(
|
||||||
|
[Description("IPv4 or IPv6 address.")] string ip,
|
||||||
|
CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var address = ParseIp(ip);
|
||||||
|
var profile = await queries.LookupIpAsync(address, ct);
|
||||||
|
if (profile is null)
|
||||||
|
{
|
||||||
|
return new IpLookupResult(address, false, null, null, null, null, null, 0, 0, 0, 0, null, null, [], 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new IpLookupResult(
|
||||||
|
profile.Ip,
|
||||||
|
true,
|
||||||
|
profile.CountryCode,
|
||||||
|
CountryNames.Display(profile.CountryCode, profile.Country),
|
||||||
|
profile.City,
|
||||||
|
Asn(profile.Asn),
|
||||||
|
profile.Provider,
|
||||||
|
profile.Catches,
|
||||||
|
profile.Rejected,
|
||||||
|
Round(profile.TotalHoldSeconds),
|
||||||
|
profile.TotalBytesSent,
|
||||||
|
profile.FirstSeen,
|
||||||
|
profile.LastSeen,
|
||||||
|
profile.Events.Select(ToItem).ToList(),
|
||||||
|
profile.EventsOmitted);
|
||||||
|
}
|
||||||
|
|
||||||
|
private DateTime? Since(string? period)
|
||||||
|
{
|
||||||
|
if (!QueryPeriod.TryParse(period, out var span))
|
||||||
|
{
|
||||||
|
throw new McpException($"Invalid period '{period}'. {PeriodDescription}");
|
||||||
|
}
|
||||||
|
|
||||||
|
return span is { } window ? timeProvider.GetUtcNow().UtcDateTime - window : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Normalize(string? period) => string.IsNullOrWhiteSpace(period) ? "all" : period.Trim().ToLowerInvariant();
|
||||||
|
|
||||||
|
private static DateTime? ParseTime(string? value, string name)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(value))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var time)
|
||||||
|
? time.UtcDateTime
|
||||||
|
: throw new McpException($"{name} must be an ISO 8601 time, e.g. 2026-11-15T08:00:00Z.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ParseIp(string value) =>
|
||||||
|
IPAddress.TryParse(value.Trim(), out var address)
|
||||||
|
? (address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address).ToString()
|
||||||
|
: throw new McpException($"'{value}' is not an IP address.");
|
||||||
|
|
||||||
|
private static string? Asn(long? asn) => asn is null ? null : $"AS{asn.Value.ToString(CultureInfo.InvariantCulture)}";
|
||||||
|
|
||||||
|
private static double Round(double seconds) => Math.Round(seconds, 3);
|
||||||
|
|
||||||
|
private static CatchItem ToItem(CatchRecord record) => new(
|
||||||
|
record.Id,
|
||||||
|
record.StartedAt,
|
||||||
|
record.EndedAt,
|
||||||
|
Round(record.DurationSeconds),
|
||||||
|
record.BytesSent,
|
||||||
|
record.Outcome.ToString(),
|
||||||
|
record.Strategy,
|
||||||
|
record.Ip,
|
||||||
|
record.CountryCode,
|
||||||
|
CountryNames.Display(record.CountryCode, record.Country),
|
||||||
|
record.City,
|
||||||
|
Asn(record.Asn),
|
||||||
|
record.Provider,
|
||||||
|
record.Target,
|
||||||
|
record.UserAgent);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace Flypaper.Web.Mcp;
|
||||||
|
|
||||||
|
public static class McpArgumentCheck
|
||||||
|
{
|
||||||
|
public static string? FindProblem(JsonElement inputSchema, IReadOnlyDictionary<string, JsonElement>? arguments)
|
||||||
|
{
|
||||||
|
var properties = inputSchema.TryGetProperty("properties", out var schemaProperties)
|
||||||
|
? schemaProperties.EnumerateObject().ToDictionary(p => p.Name, p => p.Value, StringComparer.Ordinal)
|
||||||
|
: [];
|
||||||
|
var required = inputSchema.TryGetProperty("required", out var schemaRequired)
|
||||||
|
? schemaRequired.EnumerateArray().Select(r => r.GetString()!).ToList()
|
||||||
|
: [];
|
||||||
|
var given = arguments?.Keys.ToList() ?? [];
|
||||||
|
|
||||||
|
var unknown = given.Where(name => !properties.ContainsKey(name)).ToList();
|
||||||
|
var missing = required.Where(name => !given.Contains(name, StringComparer.Ordinal)).ToList();
|
||||||
|
if (unknown.Count == 0 && missing.Count == 0)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var problems = new List<string>();
|
||||||
|
if (unknown.Count == 1 && missing.Count == 1)
|
||||||
|
{
|
||||||
|
problems.Add($"unknown parameter '{unknown[0]}'; expected '{missing[0]}'{Values(properties[missing[0]])}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
problems.AddRange(unknown.Select(name => $"unknown parameter '{name}'"));
|
||||||
|
problems.AddRange(missing.Select(name => $"missing required parameter '{name}'{Values(properties[name])}"));
|
||||||
|
}
|
||||||
|
|
||||||
|
var allowed = properties.Count == 0
|
||||||
|
? "none"
|
||||||
|
: string.Join(", ", properties.Select(p => required.Contains(p.Key) ? $"{p.Key} (required)" : p.Key));
|
||||||
|
return $"{string.Join("; ", problems)}. Parameters: {allowed}.";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Values(JsonElement property) =>
|
||||||
|
property.TryGetProperty("enum", out var values)
|
||||||
|
? $" ({string.Join("|", values.EnumerateArray().Select(v => v.GetString()))})"
|
||||||
|
: "";
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
using Flypaper.Storage.Settings;
|
||||||
|
using Microsoft.AspNetCore.Antiforgery;
|
||||||
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
using ModelContextProtocol;
|
||||||
|
using ModelContextProtocol.Protocol;
|
||||||
|
using ModelContextProtocol.Server;
|
||||||
|
|
||||||
|
namespace Flypaper.Web.Mcp;
|
||||||
|
|
||||||
|
public static class McpExtensions
|
||||||
|
{
|
||||||
|
public const string Path = "/mcp";
|
||||||
|
private const string PolicyName = "Mcp";
|
||||||
|
|
||||||
|
private const string Instructions =
|
||||||
|
"Flypaper is an HTTP tarpit. Scanning bots that probe a server (e.g. for /.env or /wp-login.php) are " +
|
||||||
|
"answered with an endless page a few bytes at a time and held as long as possible. Every such catch is " +
|
||||||
|
"stored with its time, client IP, country, network provider (ASN), requested URL, user agent, duration " +
|
||||||
|
"and bytes sent. These tools only read that data; times are ISO 8601 UTC, durations in seconds.";
|
||||||
|
|
||||||
|
private static readonly JsonSerializerOptions ToolJsonOptions = new(McpJsonUtilities.DefaultOptions)
|
||||||
|
{
|
||||||
|
DefaultIgnoreCondition = JsonIgnoreCondition.Never
|
||||||
|
};
|
||||||
|
|
||||||
|
public static IServiceCollection AddFlypaperMcp(this IServiceCollection services, IConfiguration configuration)
|
||||||
|
{
|
||||||
|
services.Configure<McpOptions>(configuration.GetSection(McpOptions.SectionName));
|
||||||
|
services.AddSingleton<McpTokenService>();
|
||||||
|
|
||||||
|
services.AddAuthentication()
|
||||||
|
.AddScheme<AuthenticationSchemeOptions, McpTokenAuthenticationHandler>(McpTokenAuthenticationHandler.SchemeName, null);
|
||||||
|
services.AddAuthorizationBuilder()
|
||||||
|
.AddPolicy(PolicyName, policy => policy
|
||||||
|
.AddAuthenticationSchemes(McpTokenAuthenticationHandler.SchemeName)
|
||||||
|
.RequireAuthenticatedUser());
|
||||||
|
|
||||||
|
services.AddMcpServer(options =>
|
||||||
|
{
|
||||||
|
options.ServerInfo = new Implementation { Name = "flypaper", Version = AppVersion.Current };
|
||||||
|
options.ServerInstructions = Instructions;
|
||||||
|
})
|
||||||
|
.WithHttpTransport(options => options.Stateless = true)
|
||||||
|
.WithTools<FlypaperTools>(ToolJsonOptions)
|
||||||
|
.WithRequestFilters(filters => filters.AddCallToolFilter(next => async (context, ct) =>
|
||||||
|
{
|
||||||
|
var tool = context.Params?.Name;
|
||||||
|
var logger = context.Services?.GetRequiredService<ILoggerFactory>().CreateLogger(typeof(FlypaperTools));
|
||||||
|
|
||||||
|
if (context.MatchedPrimitive is McpServerTool matched
|
||||||
|
&& McpArgumentCheck.FindProblem(matched.ProtocolTool.InputSchema, context.Params?.Arguments?.AsReadOnly()) is { } problem)
|
||||||
|
{
|
||||||
|
logger?.LogWarning("MCP tool {Tool} was called with invalid arguments: {Problem}", tool, problem);
|
||||||
|
return InvalidArguments(tool, problem);
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return await next(context, ct);
|
||||||
|
}
|
||||||
|
catch (ArgumentException exception)
|
||||||
|
{
|
||||||
|
logger?.LogWarning(exception, "MCP tool {Tool} was called with invalid arguments", tool);
|
||||||
|
return InvalidArguments(tool, exception.Message);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static CallToolResult InvalidArguments(string? tool, string message) => new()
|
||||||
|
{
|
||||||
|
IsError = true,
|
||||||
|
Content = [new TextContentBlock { Text = $"Invalid arguments for '{tool}': {message}" }]
|
||||||
|
};
|
||||||
|
|
||||||
|
public static IEndpointRouteBuilder MapFlypaperMcp(this IEndpointRouteBuilder app)
|
||||||
|
{
|
||||||
|
app.MapMcp(Path).RequireAuthorization(PolicyName);
|
||||||
|
|
||||||
|
app.MapPost("/mcp-tokens/{id:int}/revoke", async (int id, HttpContext context, IAntiforgery antiforgery, McpTokenStore store) =>
|
||||||
|
{
|
||||||
|
if (!await antiforgery.IsRequestValidAsync(context))
|
||||||
|
{
|
||||||
|
return Results.BadRequest();
|
||||||
|
}
|
||||||
|
|
||||||
|
await store.RevokeAsync(id, context.RequestAborted);
|
||||||
|
return Results.LocalRedirect("/settings?mcp=revoked#mcp");
|
||||||
|
});
|
||||||
|
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace Flypaper.Web.Mcp;
|
||||||
|
|
||||||
|
public sealed class McpOptions
|
||||||
|
{
|
||||||
|
public const string SectionName = "Flypaper:Mcp";
|
||||||
|
|
||||||
|
public string? Token { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
namespace Flypaper.Web.Mcp;
|
||||||
|
|
||||||
|
public sealed record CatchItem(
|
||||||
|
long Id,
|
||||||
|
DateTime StartedAt,
|
||||||
|
DateTime EndedAt,
|
||||||
|
double DurationSeconds,
|
||||||
|
long BytesSent,
|
||||||
|
string Outcome,
|
||||||
|
string Strategy,
|
||||||
|
string Ip,
|
||||||
|
string? CountryCode,
|
||||||
|
string? Country,
|
||||||
|
string? City,
|
||||||
|
string? Asn,
|
||||||
|
string? Provider,
|
||||||
|
string? Target,
|
||||||
|
string? UserAgent);
|
||||||
|
|
||||||
|
public sealed record StatsResult(
|
||||||
|
string Period,
|
||||||
|
DateTime? Since,
|
||||||
|
int Catches,
|
||||||
|
int Rejected,
|
||||||
|
int UniqueIps,
|
||||||
|
double TotalHoldSeconds,
|
||||||
|
double AverageHoldSeconds,
|
||||||
|
int ActiveTraps,
|
||||||
|
CatchItem? LongestCatch);
|
||||||
|
|
||||||
|
public sealed record CatchListResult(int Count, IReadOnlyList<CatchItem> Catches);
|
||||||
|
|
||||||
|
public sealed record TopResultItem(string Key, string? Label, int Catches, double TotalHoldSeconds);
|
||||||
|
|
||||||
|
public sealed record TopResult(string Dimension, string Period, IReadOnlyList<TopResultItem> Items);
|
||||||
|
|
||||||
|
public sealed record IpLookupResult(
|
||||||
|
string Ip,
|
||||||
|
bool Known,
|
||||||
|
string? CountryCode,
|
||||||
|
string? Country,
|
||||||
|
string? City,
|
||||||
|
string? Asn,
|
||||||
|
string? Provider,
|
||||||
|
int Catches,
|
||||||
|
int Rejected,
|
||||||
|
double TotalHoldSeconds,
|
||||||
|
long TotalBytesSent,
|
||||||
|
DateTime? FirstSeen,
|
||||||
|
DateTime? LastSeen,
|
||||||
|
IReadOnlyList<CatchItem> Events,
|
||||||
|
int EventsOmitted);
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
using System.Security.Claims;
|
||||||
|
using System.Text.Encodings.Web;
|
||||||
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Flypaper.Web.Mcp;
|
||||||
|
|
||||||
|
public sealed class McpTokenAuthenticationHandler(
|
||||||
|
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||||
|
ILoggerFactory logger,
|
||||||
|
UrlEncoder encoder,
|
||||||
|
McpTokenService tokens) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||||
|
{
|
||||||
|
public const string SchemeName = "McpToken";
|
||||||
|
|
||||||
|
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||||
|
{
|
||||||
|
var header = Request.Headers.Authorization.ToString();
|
||||||
|
if (!header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return AuthenticateResult.NoResult();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!await tokens.ValidateAsync(header["Bearer ".Length..].Trim(), Context.RequestAborted))
|
||||||
|
{
|
||||||
|
return AuthenticateResult.Fail("Invalid MCP token.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "mcp")], SchemeName);
|
||||||
|
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), SchemeName));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
|
||||||
|
{
|
||||||
|
Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||||
|
Response.Headers.WWWAuthenticate = "Bearer";
|
||||||
|
await Response.WriteAsJsonAsync(new { error = "invalid_token" });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using Flypaper.Storage.Settings;
|
||||||
|
using Microsoft.AspNetCore.WebUtilities;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Flypaper.Web.Mcp;
|
||||||
|
|
||||||
|
public sealed class McpTokenService(McpTokenStore store, IOptions<McpOptions> options)
|
||||||
|
{
|
||||||
|
private const string Prefix = "fpm_";
|
||||||
|
|
||||||
|
public bool UsesEnvironmentToken => !string.IsNullOrEmpty(options.Value.Token);
|
||||||
|
|
||||||
|
public async Task<string> CreateAsync(string name, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var token = Prefix + WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
|
||||||
|
await store.CreateAsync(name, Hash(token), ct);
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> ValidateAsync(string? token, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(token))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (UsesEnvironmentToken
|
||||||
|
&& CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(token)), SHA256.HashData(Encoding.UTF8.GetBytes(options.Value.Token!))))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return await store.UseAsync(Hash(token), ct) is not null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string Hash(string token) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(token)));
|
||||||
|
}
|
||||||
@@ -2,16 +2,24 @@ using Flypaper.Core;
|
|||||||
using Flypaper.GeoIp;
|
using Flypaper.GeoIp;
|
||||||
using Flypaper.Http;
|
using Flypaper.Http;
|
||||||
using Flypaper.Storage;
|
using Flypaper.Storage;
|
||||||
|
using Flypaper.Web;
|
||||||
using Flypaper.Web.Auth;
|
using Flypaper.Web.Auth;
|
||||||
using Flypaper.Web.Components;
|
using Flypaper.Web.Components;
|
||||||
using Flypaper.Web.Health;
|
using Flypaper.Web.Health;
|
||||||
|
using Flypaper.Web.Mcp;
|
||||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.DataProtection;
|
using Microsoft.AspNetCore.DataProtection;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
builder.WebHost.ConfigureKestrel(options => options.AddServerHeader = false);
|
var ports = builder.Configuration.GetSection(PortOptions.SectionName).Get<PortOptions>() ?? new PortOptions();
|
||||||
|
builder.WebHost.ConfigureKestrel(options =>
|
||||||
|
{
|
||||||
|
options.AddServerHeader = false;
|
||||||
|
options.ListenAnyIP(ports.Trap);
|
||||||
|
options.ListenAnyIP(ports.Dashboard);
|
||||||
|
});
|
||||||
|
|
||||||
builder.AddFlypaperStorage();
|
builder.AddFlypaperStorage();
|
||||||
builder.Services.AddRazorComponents();
|
builder.Services.AddRazorComponents();
|
||||||
@@ -25,6 +33,8 @@ if (builder.Configuration["Flypaper:DataProtection:KeysPath"] is { Length: > 0 }
|
|||||||
dataProtection.PersistKeysToFileSystem(new DirectoryInfo(keysPath));
|
dataProtection.PersistKeysToFileSystem(new DirectoryInfo(keysPath));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
builder.Services.AddFlypaperMcp(builder.Configuration);
|
||||||
|
|
||||||
builder.Services.Configure<AdminOptions>(builder.Configuration.GetSection(AdminOptions.SectionName));
|
builder.Services.Configure<AdminOptions>(builder.Configuration.GetSection(AdminOptions.SectionName));
|
||||||
builder.Services.AddSingleton<AdminAuthenticator>();
|
builder.Services.AddSingleton<AdminAuthenticator>();
|
||||||
builder.Services
|
builder.Services
|
||||||
@@ -44,6 +54,8 @@ builder.Services.AddAuthorizationBuilder()
|
|||||||
|
|
||||||
var app = builder.Build();
|
var app = builder.Build();
|
||||||
|
|
||||||
|
app.Logger.LogInformation("Flypaper {Version} starting", AppVersion.Current);
|
||||||
|
FlypaperHttpExtensions.WarnAboutRemovedSettings(app.Configuration, app.Logger);
|
||||||
await app.Services.MigrateFlypaperDatabaseAsync();
|
await app.Services.MigrateFlypaperDatabaseAsync();
|
||||||
|
|
||||||
app.UseFlypaper();
|
app.UseFlypaper();
|
||||||
@@ -61,6 +73,7 @@ app.UseAntiforgery();
|
|||||||
app.MapStaticAssets().AllowAnonymous();
|
app.MapStaticAssets().AllowAnonymous();
|
||||||
app.MapAuthEndpoints();
|
app.MapAuthEndpoints();
|
||||||
app.MapHealthEndpoint();
|
app.MapHealthEndpoint();
|
||||||
|
app.MapFlypaperMcp();
|
||||||
app.MapRazorComponents<App>();
|
app.MapRazorComponents<App>();
|
||||||
|
|
||||||
await app.RunAsync();
|
await app.RunAsync();
|
||||||
|
|||||||
@@ -6,13 +6,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"Flypaper": {
|
"Flypaper": {
|
||||||
"Http": {
|
|
||||||
"KnownHosts": [
|
|
||||||
"localhost"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"Admin": {
|
"Admin": {
|
||||||
"Password": "dev"
|
"Password": "dev"
|
||||||
|
},
|
||||||
|
"Ports": {
|
||||||
|
"Trap": 5247,
|
||||||
|
"Dashboard": 5248
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -23,24 +23,7 @@
|
|||||||
"MaxConnectionsPerIp": 10,
|
"MaxConnectionsPerIp": 10,
|
||||||
"MaxHoldDuration": "01:00:00",
|
"MaxHoldDuration": "01:00:00",
|
||||||
"Http": {
|
"Http": {
|
||||||
"KnownHosts": [],
|
"TrustedProxies": []
|
||||||
"TrustedProxies": [],
|
|
||||||
"TrapPaths": [
|
|
||||||
"/.env",
|
|
||||||
"/.env.*",
|
|
||||||
"/.git/*",
|
|
||||||
"/.aws/*",
|
|
||||||
"/.DS_Store",
|
|
||||||
"/wp-login.php",
|
|
||||||
"/wp-admin/*",
|
|
||||||
"/xmlrpc.php",
|
|
||||||
"/phpmyadmin/*",
|
|
||||||
"/vendor/phpunit/*",
|
|
||||||
"/server-status",
|
|
||||||
"/actuator/*",
|
|
||||||
"/cgi-bin/*",
|
|
||||||
"/boaform/*"
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+1148
-79
File diff suppressed because it is too large.
Load diff
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user