Compare commits
9
Commits
v0.1.1
..
570ac20a5c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
570ac20a5c | ||
|
|
393ebcdf0c | ||
|
|
f5bcc55a29 | ||
|
|
31bb8b21c2 | ||
|
|
de22f035dc | ||
|
|
6b9bf3cd5f | ||
|
|
9a56fc5b48 | ||
|
|
b9f2b0443c | ||
|
|
49a8fa1154 |
No files matched your search
+48
-1
@@ -6,6 +6,50 @@ All notable changes to Flypaper are documented in this file. The format follows
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [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
|
||||
@@ -48,6 +92,9 @@ First release.
|
||||
- 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.1.1...main
|
||||
[Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.3.1...main
|
||||
[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
|
||||
@@ -11,6 +11,7 @@
|
||||
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.15" />
|
||||
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.15" />
|
||||
<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.Sqlite" Version="10.0.15" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -11,7 +11,7 @@ the dashboard shows you who knocked: country, network provider and what they wer
|
||||
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 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 --> db[("SQLite:<br/>catches, settings")]
|
||||
you["You (LAN)"] -->|"dashboard, port 8081"| flypaper
|
||||
@@ -23,6 +23,7 @@ flowchart LR
|
||||
within limits per IP, overall and per catch.
|
||||
- Each catch is logged and stored with its origin (DB-IP GeoIP); the dashboard on port `8081`
|
||||
shows maps and tables.
|
||||
- AI assistants such as Claude can query the catches over MCP: [docs/mcp.md](docs/mcp.md).
|
||||
|
||||
More: [how it works and all features](docs/overview.md).
|
||||
|
||||
@@ -86,8 +87,7 @@ server {
|
||||
}
|
||||
```
|
||||
|
||||
Nginx Proxy Manager, Caddy, Traefik and bait paths on your real domains:
|
||||
[docs/reverse-proxy.md](docs/reverse-proxy.md).
|
||||
Nginx Proxy Manager, Caddy and Traefik: [docs/reverse-proxy.md](docs/reverse-proxy.md).
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -97,10 +97,9 @@ Nothing is required. The most useful optional environment variables:
|
||||
|---|---|
|
||||
| `Flypaper__Admin__Password` | Fixes the dashboard password instead of setting it on first visit |
|
||||
| `Flypaper__Http__TrustedProxies__0` | Proxy IP or CIDR allowed to set `X-Real-IP` (default: private networks) |
|
||||
| `Flypaper__Http__KnownHosts__0` | Host that is caught only on trap paths |
|
||||
| `TZ` | Time zone for the dashboard |
|
||||
|
||||
Trap paths, limits and retention are changed on the dashboard's settings page. All variables
|
||||
Hold method, limits and retention are changed on the dashboard's settings page. All variables
|
||||
and settings: [docs/configuration.md](docs/configuration.md).
|
||||
|
||||
## Security
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
# .gitea/workflows/deploy.yml, not pasted into the Compose Manager.
|
||||
#
|
||||
# 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 has its own
|
||||
# site for unknown hosts). The dashboard has its own
|
||||
# port 8081, published only to the LAN: http://192.168.1.14:44307.
|
||||
#
|
||||
# `restart: always`, not `unless-stopped`: Unraid stops every container explicitly
|
||||
|
||||
@@ -15,11 +15,12 @@ All optional. Read at startup; list entries need an index (`__0`, `__1`, ...).
|
||||
|---|---|---|
|
||||
| `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__Http__KnownHosts__0` | Hosts that are caught only on trap paths (`*.example.com` allowed), see [reverse proxy](reverse-proxy.md#what-to-send-to-flypaper) | none |
|
||||
| `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 |
|
||||
@@ -30,13 +31,14 @@ The defaults of the runtime settings below can also be set this way, e.g.
|
||||
## Runtime settings
|
||||
|
||||
Changed on the dashboard's settings page, stored in the database, effective immediately. The
|
||||
reset button removes all saved values.
|
||||
general reset button removes all saved values; the hold method section has its own reset.
|
||||
|
||||
| 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/*` |
|
||||
| Extra known hosts (merged with `KnownHosts`) | none |
|
||||
| Maximum hold time per catch | `01:00:00` |
|
||||
| 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` |
|
||||
|
||||
+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.
|
||||
+8
-7
@@ -11,15 +11,14 @@ else, and every catch is logged with its origin for you to look at.
|
||||
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 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 --> 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, optionally also a few bait paths on your real
|
||||
domains.
|
||||
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
|
||||
@@ -31,19 +30,21 @@ flowchart LR
|
||||
|
||||
## Features
|
||||
|
||||
- **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
|
||||
- **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**: trap paths, extra known hosts, limits and retention, changed at runtime
|
||||
- **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
|
||||
|
||||
+3
-38
@@ -20,17 +20,9 @@ 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. Every request on the trap port is
|
||||
caught, so nothing else is needed.
|
||||
|
||||
*Known hosts* (optional) change this for hosts you list: on the trap port, a known host is
|
||||
caught only on the configured trap paths, and its other paths get a plain `404` without being
|
||||
logged. That is useful if your proxy forwards more than the bait paths of a real domain, for
|
||||
example a whole location. Unknown hosts are always caught. The dashboard is never reachable
|
||||
on the trap port.
|
||||
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
|
||||
@@ -73,20 +65,6 @@ Put Flypaper into the same Docker network as NPM (the examples use the container
|
||||
|
||||
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
|
||||
@@ -122,16 +100,6 @@ With Flypaper on the same host, nothing else is needed: loopback is trusted by d
|
||||
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
|
||||
@@ -146,8 +114,5 @@ labels:
|
||||
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"
|
||||
```
|
||||
@@ -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<IRandomSource, SystemRandomSource>();
|
||||
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<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(
|
||||
TrapContext context,
|
||||
Func<CancellationToken, ValueTask<ITrapChannel>> openChannel,
|
||||
Func<ITarpitStrategy, CancellationToken, ValueTask<ITrapChannel>> openChannel,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var session = context.Session;
|
||||
@@ -30,6 +30,7 @@ public sealed partial class TrapRunner(
|
||||
}
|
||||
|
||||
using var _ = lease;
|
||||
var description = strategy is IStrategyDetails details ? details.Describe() : strategy.Name;
|
||||
using var hold = new CancellationTokenSource(options.CurrentValue.MaxHoldDuration, timeProvider);
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
|
||||
|
||||
@@ -37,7 +38,7 @@ public sealed partial class TrapRunner(
|
||||
var outcome = TrapOutcome.Completed;
|
||||
try
|
||||
{
|
||||
channel = new CountingTrapChannel(await openChannel(linked.Token));
|
||||
channel = new CountingTrapChannel(await openChannel(strategy, linked.Token));
|
||||
await strategy.RunAsync(channel, linked.Token);
|
||||
}
|
||||
catch (OperationCanceledException) when (linked.IsCancellationRequested)
|
||||
@@ -51,7 +52,7 @@ public sealed partial class TrapRunner(
|
||||
outcome = TrapOutcome.ClientAborted;
|
||||
}
|
||||
|
||||
Publish(context, strategy.Name, channel?.BytesSent ?? 0, outcome);
|
||||
Publish(context, description, channel?.BytesSent ?? 0, 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;
|
||||
|
||||
public sealed record RuntimeSettings(
|
||||
IReadOnlyList<string> TrapPaths,
|
||||
int MaxConnections,
|
||||
int MaxConnectionsPerIp,
|
||||
TimeSpan MaxHoldDuration,
|
||||
IReadOnlyList<string> ExtraKnownHosts,
|
||||
int RetentionDays,
|
||||
bool IgnorePrivateNetworks)
|
||||
{
|
||||
public IReadOnlyDictionary<string, string> ToConfiguration() => new Dictionary<string, string>
|
||||
{
|
||||
[SettingKeys.TrapPaths] = SettingsList.Join(TrapPaths),
|
||||
[SettingKeys.MaxConnections] = MaxConnections.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.IgnorePrivateNetworks] = IgnorePrivateNetworks ? "true" : "false"
|
||||
};
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
namespace Flypaper.Core.Settings;
|
||||
|
||||
public sealed record RuntimeSettingsInput(
|
||||
string? TrapPaths,
|
||||
string? MaxConnections,
|
||||
string? MaxConnectionsPerIp,
|
||||
string? MaxHoldDuration,
|
||||
string? ExtraKnownHosts,
|
||||
string? RetentionDays,
|
||||
bool IgnorePrivateNetworks);
|
||||
@@ -1,29 +1,23 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using Flypaper.Core.Strategies;
|
||||
|
||||
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 MaxRetentionDays = 3650;
|
||||
|
||||
private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1);
|
||||
private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7);
|
||||
|
||||
[GeneratedRegex(@"^(\*\.)?[A-Za-z0-9]([A-Za-z0-9.\-]*[A-Za-z0-9])?$")]
|
||||
private static partial Regex HostPattern();
|
||||
private const int MinDelayMs = 10;
|
||||
private const int MaxDelayMs = 30_000;
|
||||
private const int MaxChunkSize = 4096;
|
||||
|
||||
public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input)
|
||||
{
|
||||
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 perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), 1, MaxLimit, 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(
|
||||
paths!,
|
||||
maxConnections!.Value,
|
||||
perIp!.Value,
|
||||
hold!.Value,
|
||||
hosts!,
|
||||
retention!.Value,
|
||||
input.IgnorePrivateNetworks);
|
||||
return new RuntimeSettingsParseResult(settings, errors);
|
||||
}
|
||||
|
||||
private static string[]? ParseList(
|
||||
string? raw,
|
||||
string field,
|
||||
Func<string, string?> validate,
|
||||
Dictionary<string, string> errors)
|
||||
public static HoldMethodParseResult ParseHoldMethod(HoldMethodInput input)
|
||||
{
|
||||
var lines = (raw ?? string.Empty)
|
||||
.Split(['\r', '\n'], StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
|
||||
var errors = new Dictionary<string, string>();
|
||||
|
||||
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.";
|
||||
return null;
|
||||
errors[nameof(input.Content)] = "Bitte eine Methode wählen.";
|
||||
}
|
||||
|
||||
var problems = new List<string>();
|
||||
for (var i = 0; i < lines.Length; i++)
|
||||
var minDelay = ParseInt(input.MinDelayMs, nameof(input.MinDelayMs), MinDelayMs, MaxDelayMs, errors);
|
||||
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)
|
||||
{
|
||||
problems.Add($"„{lines[i]}“: {problem}");
|
||||
}
|
||||
errors[nameof(input.MaxDelayMs)] = "Darf nicht kleiner sein als das Minimum.";
|
||||
}
|
||||
|
||||
if (problems.Count > 0)
|
||||
if (minChunk > maxChunk)
|
||||
{
|
||||
errors[field] = string.Join(" ", problems.Take(3)) + (problems.Count > 3 ? $" (+{problems.Count - 3} weitere)" : "");
|
||||
return null;
|
||||
errors[nameof(input.MaxChunkSize)] = "Darf nicht kleiner sein als das Minimum.";
|
||||
}
|
||||
|
||||
return lines.Distinct(StringComparer.Ordinal).ToArray();
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
return new HoldMethodParseResult(null, errors);
|
||||
}
|
||||
|
||||
private static string? ValidatePath(string path)
|
||||
{
|
||||
if (path[0] != '/')
|
||||
{
|
||||
return "muss mit / beginnen.";
|
||||
}
|
||||
|
||||
if (path.Length > MaxPathLength)
|
||||
{
|
||||
return $"höchstens {MaxPathLength} Zeichen.";
|
||||
}
|
||||
|
||||
if (path.Any(char.IsWhiteSpace))
|
||||
{
|
||||
return "darf keine Leerzeichen enthalten.";
|
||||
}
|
||||
|
||||
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).";
|
||||
return new HoldMethodParseResult(
|
||||
new HoldMethodSettings(
|
||||
content!.Value,
|
||||
TimeSpan.FromMilliseconds(minDelay!.Value),
|
||||
TimeSpan.FromMilliseconds(maxDelay!.Value),
|
||||
minChunk!.Value,
|
||||
maxChunk!.Value,
|
||||
hold!.Value),
|
||||
errors);
|
||||
}
|
||||
|
||||
private static TimeSpan? ParseTimeSpan(
|
||||
|
||||
@@ -5,19 +5,20 @@ public static class SettingKeys
|
||||
public const string MaxConnections = "Flypaper:MaxConnections";
|
||||
public const string MaxConnectionsPerIp = "Flypaper:MaxConnectionsPerIp";
|
||||
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 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)
|
||||
{
|
||||
MaxConnections,
|
||||
MaxConnectionsPerIp,
|
||||
MaxHoldDuration,
|
||||
TrapPaths,
|
||||
ExtraKnownHosts,
|
||||
IgnorePrivateNetworks,
|
||||
RetentionDays
|
||||
};
|
||||
public static readonly IReadOnlyList<string> General =
|
||||
[MaxConnections, MaxConnectionsPerIp, IgnorePrivateNetworks, RetentionDays];
|
||||
|
||||
public static readonly IReadOnlyList<string> HoldMethod =
|
||||
[DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, MaxHoldDuration];
|
||||
|
||||
public static readonly IReadOnlySet<string> All =
|
||||
new HashSet<string>(General.Concat(HoldMethod), StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
@@ -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 DripContent Content { get; set; } = DripContent.Html;
|
||||
|
||||
public TimeSpan MinDelay { get; set; } = TimeSpan.FromMilliseconds(50);
|
||||
|
||||
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; }
|
||||
""";
|
||||
|
||||
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 =
|
||||
["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);
|
||||
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();
|
||||
@@ -145,8 +127,8 @@ public static class HtmlContent
|
||||
continue;
|
||||
}
|
||||
|
||||
var word = Pick(random, Vocabulary);
|
||||
builder.Append(i == 0 ? Capitalize(word) : word);
|
||||
var word = LoremText.Word(random);
|
||||
builder.Append(i == 0 ? LoremText.Capitalize(word) : word);
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
var text = Phrase(random, words);
|
||||
var text = LoremText.Phrase(random, words);
|
||||
var slug = text.Replace(' ', '-');
|
||||
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 Phrase(IRandomSource random, int count) =>
|
||||
string.Join(' ', Enumerable.Range(0, count).Select(_ => Pick(random, Vocabulary)));
|
||||
private static string Title(IRandomSource random, int min, int max) => LoremText.Capitalize(LoremText.Phrase(random, random.Next(min, max + 1)));
|
||||
|
||||
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.Models;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Core.Strategies;
|
||||
@@ -7,19 +6,13 @@ namespace Flypaper.Core.Strategies;
|
||||
public sealed class HtmlDripStrategy(
|
||||
IOptionsMonitor<DripOptions> options,
|
||||
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)
|
||||
{
|
||||
foreach (var step in DripSchedule.Create(HtmlContent.Generate(random), random, options.CurrentValue))
|
||||
{
|
||||
ct.ThrowIfCancellationRequested();
|
||||
await channel.WriteAsync(step.Chunk, ct);
|
||||
await Task.Delay(step.Delay, timeProvider, ct);
|
||||
}
|
||||
}
|
||||
public override string MediaType => "text/html; charset=utf-8";
|
||||
|
||||
protected override IEnumerable<string> Content(IRandomSource random) => HtmlContent.Generate(random);
|
||||
}
|
||||
@@ -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,13 +1,11 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using Flypaper.Core.Settings;
|
||||
using Flypaper.Http.Matching;
|
||||
using Flypaper.Http.Middleware;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Http;
|
||||
@@ -16,20 +14,18 @@ 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)
|
||||
{
|
||||
services.Configure<HttpTrapOptions>(configuration.GetSection(HttpTrapOptions.SectionName));
|
||||
services.Configure<PortOptions>(configuration.GetSection(PortOptions.SectionName));
|
||||
services.PostConfigure<HttpTrapOptions>(options =>
|
||||
{
|
||||
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>()
|
||||
.Configure<IOptions<HttpTrapOptions>>((forwarded, trap) =>
|
||||
@@ -55,6 +51,16 @@ public static class FlypaperHttpExtensions
|
||||
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) =>
|
||||
IPAddress.Parse(address).AddressFamily == AddressFamily.InterNetworkV6 ? 128 : 32;
|
||||
}
|
||||
@@ -6,13 +6,5 @@ public sealed class HttpTrapOptions
|
||||
|
||||
public const string HealthPath = "/health";
|
||||
|
||||
public string[] KnownHosts { get; set; } = [];
|
||||
|
||||
public string[] TrapPaths { 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,7 +3,6 @@ using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Core.Networking;
|
||||
using Flypaper.Core.Runtime;
|
||||
using Flypaper.Http.Matching;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
|
||||
@@ -13,7 +12,6 @@ namespace Flypaper.Http.Middleware;
|
||||
|
||||
internal sealed class FlypaperMiddleware(
|
||||
RequestDelegate next,
|
||||
TrapMatcher matcher,
|
||||
TrapRunner runner,
|
||||
IOptions<PortOptions> ports,
|
||||
TimeProvider timeProvider)
|
||||
@@ -27,11 +25,6 @@ internal sealed class FlypaperMiddleware(
|
||||
}
|
||||
|
||||
var request = context.Request;
|
||||
if (matcher.Match(request.Host.Host, request.Path.Value) == TrapMatch.None)
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
return;
|
||||
}
|
||||
|
||||
var session = new TrapSession(
|
||||
Guid.NewGuid(),
|
||||
@@ -46,7 +39,7 @@ internal sealed class FlypaperMiddleware(
|
||||
|
||||
var outcome = await runner.RunAsync(
|
||||
trapContext,
|
||||
ct => OpenChannelAsync(context, session, ct),
|
||||
(strategy, ct) => OpenChannelAsync(context, session, strategy, ct),
|
||||
context.RequestAborted);
|
||||
|
||||
if (outcome == TrapOutcome.Rejected && !context.Response.HasStarted)
|
||||
@@ -66,6 +59,7 @@ internal sealed class FlypaperMiddleware(
|
||||
private static async ValueTask<ITrapChannel> OpenChannelAsync(
|
||||
HttpContext context,
|
||||
TrapSession session,
|
||||
ITarpitStrategy strategy,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var minDataRate = context.Features.Get<IHttpMinResponseDataRateFeature>();
|
||||
@@ -78,7 +72,7 @@ internal sealed class FlypaperMiddleware(
|
||||
|
||||
var response = context.Response;
|
||||
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["X-Accel-Buffering"] = "no";
|
||||
await response.StartAsync(ct);
|
||||
|
||||
@@ -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<McpTokenEntity> McpTokens => Set<McpTokenEntity>();
|
||||
|
||||
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) =>
|
||||
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
|
||||
|
||||
@@ -36,5 +38,10 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
|
||||
var setting = modelBuilder.Entity<SettingEntity>();
|
||||
setting.HasKey(e => e.Key);
|
||||
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.Events;
|
||||
using Flypaper.Storage.Maintenance;
|
||||
using Flypaper.Storage.Queries;
|
||||
using Flypaper.Storage.Settings;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
@@ -21,6 +22,7 @@ public static class FlypaperStorageExtensions
|
||||
builder.Services.AddSingleton(source);
|
||||
builder.Services.AddSingleton<RuntimeSettingsStore>();
|
||||
builder.Services.AddSingleton<AdminCredentialStore>();
|
||||
builder.Services.AddSingleton<McpTokenStore>();
|
||||
builder.Services.Configure<RetentionOptions>(builder.Configuration.GetSection(RetentionOptions.SectionName));
|
||||
builder.Services.AddFlypaperStorage(connectionString);
|
||||
|
||||
@@ -35,6 +37,7 @@ public static class FlypaperStorageExtensions
|
||||
services.AddHostedService<TrapEventWriter>();
|
||||
services.AddHostedService<OriginBackfill>();
|
||||
services.AddSingleton<DashboardQueries>();
|
||||
services.AddSingleton<CatchQueries>();
|
||||
services.AddSingleton<TrapDataMaintenance>();
|
||||
services.AddHostedService<RetentionCleanup>();
|
||||
return services;
|
||||
|
||||
@@ -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
|
||||
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")
|
||||
|
||||
@@ -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,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;
|
||||
}
|
||||
}
|
||||
@@ -12,33 +12,42 @@ public sealed partial class RuntimeSettingsStore(
|
||||
{
|
||||
private static readonly string[] RuntimeKeys = SettingKeys.All.ToArray();
|
||||
|
||||
public async Task SaveAsync(RuntimeSettings settings, CancellationToken ct = default)
|
||||
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 transaction = await db.Database.BeginTransactionAsync(ct);
|
||||
await RuntimeSettings(db).ExecuteDeleteAsync(ct);
|
||||
db.Settings.AddRange(settings.ToConfiguration().Select(pair => new SettingEntity { Key = pair.Key, Value = pair.Value }));
|
||||
await RuntimeSettings(db, values.Keys.ToArray()).ExecuteDeleteAsync(ct);
|
||||
db.Settings.AddRange(values.Select(pair => new SettingEntity { Key = pair.Key, Value = pair.Value }));
|
||||
await db.SaveChangesAsync(ct);
|
||||
await transaction.CommitAsync(ct);
|
||||
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);
|
||||
await RuntimeSettings(db).ExecuteDeleteAsync(ct);
|
||||
Reload();
|
||||
var selected = keys?.Where(key => SettingKeys.All.Contains(key)).ToArray() ?? RuntimeKeys;
|
||||
return db.Settings.Where(setting => selected.Contains(setting.Key));
|
||||
}
|
||||
|
||||
public async Task<bool> HasOverridesAsync(CancellationToken ct = default)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
return await RuntimeSettings(db).AnyAsync(ct);
|
||||
}
|
||||
|
||||
private static IQueryable<SettingEntity> RuntimeSettings(FlypaperDbContext db) =>
|
||||
db.Settings.Where(setting => RuntimeKeys.Contains(setting.Key));
|
||||
|
||||
private void Reload()
|
||||
{
|
||||
if (!source.TryReload())
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
<main class="page">
|
||||
<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="/settings">Einstellungen</NavLink>
|
||||
<form method="post" action="/auth/logout" class="logout">
|
||||
|
||||
@@ -1,48 +1,93 @@
|
||||
@page "/"
|
||||
@using Flypaper.Core.Abstractions
|
||||
@using Flypaper.Http
|
||||
@using Microsoft.Extensions.Options
|
||||
@using Flypaper.Storage.Dashboard
|
||||
@using Flypaper.Storage.Entities
|
||||
@inject DashboardQueries Queries
|
||||
@inject IConnectionGovernor Governor
|
||||
@inject IOptions<PortOptions> Ports
|
||||
|
||||
<PageTitle>Flypaper</PageTitle>
|
||||
<HeadContent>
|
||||
<meta http-equiv="refresh" content="30" />
|
||||
</HeadContent>
|
||||
|
||||
<header class="top">
|
||||
<h1>Flypaper</h1>
|
||||
<span class="muted">Stand @_loadedAt.ToString("HH:mm:ss") · aktualisiert alle 30 s</span>
|
||||
<header class="page-head">
|
||||
<h1>Übersicht</h1>
|
||||
<p><span class="live-dot" aria-hidden="true"></span>Stand @_loadedAt.ToString("HH:mm:ss") · aktualisiert alle 30 s</p>
|
||||
</header>
|
||||
|
||||
@if (_data is { } data)
|
||||
{
|
||||
var active = Governor.ActiveConnections;
|
||||
var tabs = TopTabs(data);
|
||||
<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"><span class="label">Letzte 24 h</span><span class="value">@data.CatchesLast24Hours.ToString("N0")</span></div>
|
||||
<div class="metric"><span class="label">Aktiv</span><span class="value">@Governor.ActiveConnections.ToString("N0")</span></div>
|
||||
<div class="metric"><span class="label">Eindeutige IPs</span><span class="value">@data.UniqueIps.ToString("N0")</span></div>
|
||||
<div class="metric"><span class="label">Haltezeit gesamt</span><span class="value">@Formatting.Duration(data.TotalHoldTime)</span></div>
|
||||
<div class="metric"><span class="label">Abgelehnt</span><span class="value">@data.Rejected.ToString("N0")</span></div>
|
||||
<div class="metric metric-hero @(active > 0 ? "live" : null)">
|
||||
<span class="label">Gerade in der Falle</span>
|
||||
<span class="value">@active.ToString("N0")</span>
|
||||
<span class="sub">@(active == 1 ? "Bot wird festgehalten" : "Bots werden festgehalten")</span>
|
||||
</div>
|
||||
<div class="metric metric-hero">
|
||||
<span class="label">Fänge gesamt</span>
|
||||
<span class="value">@data.TotalCatches.ToString("N0")</span>
|
||||
<span class="sub">+@data.CatchesLast24Hours.ToString("N0") in den letzten 24 h</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<span class="label">Eindeutige IPs</span>
|
||||
<span class="value">@data.UniqueIps.ToString("N0")</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<span class="label">Haltezeit gesamt</span>
|
||||
<span class="value">@Formatting.Duration(data.TotalHoldTime)</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<span class="label">Abgelehnt</span>
|
||||
<span class="value">@data.Rejected.ToString("N0")</span>
|
||||
<span class="sub">wegen Verbindungslimits</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<WorldMap CatchesByCountry="data.CatchesByCountry" />
|
||||
|
||||
<section class="tops">
|
||||
<TopTable Title="Top 10 Länder" KeyLabel="Land" Entries="data.TopCountries" ShowFlags="true" LabelFormatter="CountryNames.Display" />
|
||||
<TopTable Title="Top 10 Provider (ASN)" KeyLabel="Provider" Entries="data.TopProviders" />
|
||||
<TopTable Title="Top 10 IPs" KeyLabel="IP" Entries="data.TopIps" />
|
||||
<TopTable Title="Top 10 Ziele" KeyLabel="Ziel" Entries="data.TopTargets" KeyFormatter="Formatting.Target" />
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<h2>Letzte 50 Fänge <span class="hint">Zeile anklicken zum Aufklappen</span></h2>
|
||||
@if (data.Recent.Count == 0)
|
||||
@if (data.TotalCatches == 0)
|
||||
{
|
||||
<p class="muted">Noch nichts gefangen.</p>
|
||||
<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>
|
||||
}
|
||||
else
|
||||
|
||||
<section class="origin">
|
||||
<WorldMap CatchesByCountry="data.CatchesByCountry" />
|
||||
<section class="card tops-card">
|
||||
<h2 id="tops-title">Top 10</h2>
|
||||
<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" />
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
</section>
|
||||
|
||||
@if (data.TotalCatches > 0)
|
||||
{
|
||||
<section class="card">
|
||||
<div class="card-head">
|
||||
<h2>Letzte 50 Fänge</h2>
|
||||
<span class="hint">Zeile anklicken zum Aufklappen</span>
|
||||
</div>
|
||||
<div class="scroll">
|
||||
<table class="recent-table">
|
||||
<thead>
|
||||
@@ -97,9 +142,9 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
}
|
||||
|
||||
<script src="@Assets["dashboard.js"]" defer></script>
|
||||
|
||||
@@ -113,6 +158,23 @@
|
||||
_loadedAt = DateTime.Now;
|
||||
}
|
||||
|
||||
private static IReadOnlyList<TopTab> TopTabs(DashboardData data) =>
|
||||
[
|
||||
new("countries", "Länder", "Land", data.TopCountries, ShowFlags: true, LabelFormatter: CountryNames.Display),
|
||||
new("providers", "Provider", "Provider", data.TopProviders),
|
||||
new("ips", "IPs", "IP", data.TopIps),
|
||||
new("targets", "Ziele", "Ziel", data.TopTargets, KeyFormatter: Formatting.Target)
|
||||
];
|
||||
|
||||
private static string Origin(TrapEventEntity trapEvent) =>
|
||||
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,
|
||||
bool ShowFlags = false,
|
||||
Func<string?, string?>? KeyFormatter = null,
|
||||
Func<string?, string?, string?>? LabelFormatter = null);
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
@using System.Globalization
|
||||
@using Flypaper.Storage.Dashboard
|
||||
<section class="card">
|
||||
<h2>@Title</h2>
|
||||
|
||||
@if (Entries.Count == 0)
|
||||
{
|
||||
<p class="muted">Keine Daten.</p>
|
||||
<p class="empty">Noch keine Einträge.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -23,8 +23,9 @@
|
||||
<tbody>
|
||||
@foreach (var entry in Entries)
|
||||
{
|
||||
<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>
|
||||
var share = (entry.Count * 100.0 / Entries[0].Count).ToString("0.#", CultureInfo.InvariantCulture);
|
||||
<tr data-expand="@($"{KeyLabel}:{entry.Key}")" tabindex="0" aria-expanded="false" style="--share: @(share)%">
|
||||
<td class="mono clip bar" 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>
|
||||
@@ -32,11 +33,8 @@
|
||||
</tbody>
|
||||
</table>
|
||||
}
|
||||
</section>
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired] public required string Title { get; set; }
|
||||
|
||||
[Parameter, EditorRequired] public required string KeyLabel { get; set; }
|
||||
|
||||
[Parameter, EditorRequired] public required IReadOnlyList<TopEntry> Entries { get; set; }
|
||||
|
||||
@@ -1,7 +1,22 @@
|
||||
@using System.Globalization
|
||||
|
||||
<section class="card">
|
||||
<section class="card map-card">
|
||||
<div class="card-head">
|
||||
<h2>Herkunft</h2>
|
||||
@if (_max > 0)
|
||||
{
|
||||
<div class="map-legend" aria-label="Fänge pro Land">
|
||||
<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>@_max.ToString("N0")</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
<div class="map-wrap">
|
||||
<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">
|
||||
@foreach (var country in Map.Countries)
|
||||
{
|
||||
@@ -23,13 +38,10 @@
|
||||
}
|
||||
}
|
||||
</svg>
|
||||
<div class="map-legend">
|
||||
<span>0</span>
|
||||
@for (var level = 0; level <= Levels; level++)
|
||||
@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>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -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", CultureInfo.GetCultureInfo("de-DE"));
|
||||
}
|
||||
}
|
||||
|
||||
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; }
|
||||
}
|
||||
@@ -2,38 +2,31 @@
|
||||
@inject AdminAuthenticator Admin
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<section class="card form">
|
||||
<h2>Admin-Passwort</h2>
|
||||
|
||||
<SettingsSection Id="password" Title="Admin-Passwort" Description="Das Passwort für dieses Dashboard. Gespeichert wird nur ein gesalzener Hash.">
|
||||
@if (Changed == "changed")
|
||||
{
|
||||
<div class="banner ok">Passwort geändert.</div>
|
||||
<Notice>Passwort geändert.</Notice>
|
||||
}
|
||||
|
||||
@if (Admin.UsesEnvironmentPassword)
|
||||
{
|
||||
<p class="muted">Das Passwort kommt aus der Umgebungsvariable <code>Flypaper__Admin__Password</code> und lässt sich nur dort ändern.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<EditForm Model="Model" FormName="password" OnSubmit="ChangeAsync" action="/settings" class="form">
|
||||
<label for="current-password">Aktuelles Passwort</label>
|
||||
<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" />
|
||||
<FieldError Errors="_errors" Field="@nameof(PasswordModel.Current)" />
|
||||
|
||||
<label for="new-password">Neues Passwort <span class="muted">(mindestens @AdminAuthenticator.MinimumPasswordLength Zeichen)</span></label>
|
||||
</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" />
|
||||
|
||||
<label for="confirm-password">Neues Passwort wiederholen</label>
|
||||
</SettingsField>
|
||||
<SettingsField Label="Neues Passwort wiederholen" For="confirm-password">
|
||||
<InputText id="confirm-password" type="password" autocomplete="new-password" @bind-Value="Model!.Confirmation" />
|
||||
<FieldError Errors="_errors" Field="@nameof(PasswordModel.New)" />
|
||||
|
||||
<div class="actions">
|
||||
<button type="submit">Passwort ändern</button>
|
||||
</SettingsField>
|
||||
</div>
|
||||
</div>
|
||||
</EditForm>
|
||||
}
|
||||
</section>
|
||||
<footer class="s-foot">
|
||||
<button type="submit" form="password-form">Passwort ändern</button>
|
||||
</footer>
|
||||
</SettingsSection>
|
||||
|
||||
@code {
|
||||
private readonly Dictionary<string, string> _errors = [];
|
||||
@@ -58,6 +51,6 @@
|
||||
return;
|
||||
}
|
||||
|
||||
Navigation.NavigateTo("/settings?password=changed");
|
||||
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 string? TrapPaths { get; set; }
|
||||
|
||||
public string? MaxConnections { get; set; }
|
||||
|
||||
public string? MaxConnectionsPerIp { get; set; }
|
||||
|
||||
public string? MaxHoldDuration { get; set; }
|
||||
|
||||
public string? ExtraKnownHosts { get; set; }
|
||||
|
||||
public string? RetentionDays { get; set; }
|
||||
|
||||
public bool IgnorePrivateNetworks { get; set; }
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
@using Microsoft.Data.Sqlite
|
||||
@using Microsoft.Extensions.Options
|
||||
@inject IOptionsMonitor<FlypaperOptions> Core
|
||||
@inject IOptionsMonitor<HttpTrapOptions> Http
|
||||
@inject IOptionsMonitor<RetentionOptions> Retention
|
||||
@inject IConfiguration Configuration
|
||||
@inject RuntimeSettingsStore Store
|
||||
@@ -19,97 +18,103 @@
|
||||
|
||||
<PageTitle>Flypaper · Einstellungen</PageTitle>
|
||||
|
||||
<header class="top">
|
||||
<div class="settings">
|
||||
<header class="page-head">
|
||||
<h1>Einstellungen</h1>
|
||||
@if (_hasOverrides)
|
||||
{
|
||||
<span class="badge">Überschrieben</span>
|
||||
}
|
||||
<p>Änderungen gelten sofort, ohne Neustart. Werte aus Umgebungsvariablen dienen als Standard.</p>
|
||||
</header>
|
||||
|
||||
<div class="settings-layout">
|
||||
<nav class="settings-nav" aria-label="Abschnitte">
|
||||
<a href="settings#hold-method">Haltemethode</a>
|
||||
<a href="settings#connections">Verbindungen & Speicherung</a>
|
||||
<a href="settings#data">Daten</a>
|
||||
@if (!Admin.UsesEnvironmentPassword)
|
||||
{
|
||||
<a href="settings#password">Admin-Passwort</a>
|
||||
}
|
||||
<a href="settings#mcp">MCP-Zugriff</a>
|
||||
<a href="settings#system">System</a>
|
||||
</nav>
|
||||
|
||||
<div class="settings-sections">
|
||||
<HoldMethodSection />
|
||||
|
||||
<SettingsSection Id="connections" Title="Verbindungen & Speicherung" Description="Wie viele Bots gleichzeitig festgehalten werden und wie lange Fänge gespeichert bleiben." Badge="@(_generalOverrides ? "Angepasst" : null)">
|
||||
@if (Saved == "1")
|
||||
{
|
||||
<div class="banner ok">Gespeichert. Die Änderungen gelten sofort.</div>
|
||||
}
|
||||
else if (Saved == "reset")
|
||||
{
|
||||
<div class="banner ok">Auf Standard zurückgesetzt.</div>
|
||||
<Notice>Gespeichert. Gilt ab sofort.</Notice>
|
||||
}
|
||||
|
||||
<EditForm Model="Model" FormName="settings" OnSubmit="Save" action="/settings" class="card form">
|
||||
<h2>Anpassbar</h2>
|
||||
|
||||
<label for="trap-paths">Fallenpfade <span class="muted">(einer pro Zeile, mit / am Anfang, * am Ende als Präfix)</span></label>
|
||||
<InputTextArea id="trap-paths" @bind-Value="Model!.TrapPaths" rows="10" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.TrapPaths)" />
|
||||
|
||||
<label for="hosts">Bekannte Hosts <span class="muted">(einer pro Zeile, z. B. beispiel.de oder *.beispiel.de; werden auf dem Fallen-Port nur bei Fallenpfaden gefangen, sonst 404)</span></label>
|
||||
<InputTextArea id="hosts" @bind-Value="Model!.ExtraKnownHosts" rows="4" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.ExtraKnownHosts)" />
|
||||
|
||||
<div class="grid">
|
||||
<div>
|
||||
<label for="hold">Maximale Haltedauer <span class="muted">(hh:mm:ss)</span></label>
|
||||
<InputText id="hold" @bind-Value="Model!.MaxHoldDuration" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.MaxHoldDuration)" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="max">Max. Verbindungen gesamt</label>
|
||||
<InputText id="max" @bind-Value="Model!.MaxConnections" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.MaxConnections)" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="per-ip">Max. Verbindungen pro IP</label>
|
||||
<InputText id="per-ip" @bind-Value="Model!.MaxConnectionsPerIp" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.MaxConnectionsPerIp)" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="retention">Fänge aufbewahren <span class="muted">(Tage, 0 = unbegrenzt)</span></label>
|
||||
<InputText id="retention" @bind-Value="Model!.RetentionDays" class="mono" />
|
||||
<FieldError Errors="_errors" Field="@nameof(SettingsModel.RetentionDays)" />
|
||||
</div>
|
||||
<EditForm Model="Model" FormName="settings" OnSubmit="Save" action="/settings#connections" id="connections-form">
|
||||
<div class="s-body">
|
||||
<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>
|
||||
|
||||
<label class="check">
|
||||
<InputCheckbox @bind-Value="Model!.IgnorePrivateNetworks" />
|
||||
Fänge aus privaten Netzen nicht speichern <span class="muted">(die Falle greift trotzdem)</span>
|
||||
<label class="switch-row">
|
||||
<InputCheckbox class="switch" @bind-Value="Model!.IgnorePrivateNetworks" />
|
||||
<span>
|
||||
<strong>Fänge aus privaten Netzen nicht speichern</strong>
|
||||
<span class="muted">Die Falle greift trotzdem. Praktisch, damit eigene Tests die Statistik nicht verfälschen.</span>
|
||||
</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>
|
||||
<footer class="s-foot">
|
||||
<button type="submit" form="connections-form">Speichern</button>
|
||||
</footer>
|
||||
</SettingsSection>
|
||||
|
||||
<TrapDataSection />
|
||||
|
||||
@if (!Admin.UsesEnvironmentPassword)
|
||||
{
|
||||
<PasswordSection />
|
||||
}
|
||||
|
||||
<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.UsesEnvironmentPassword ? "per Umgebungsvariable" : "im Dashboard festgelegt")</td></tr>
|
||||
<tr><th>Ports</th><td class="mono">Falle @Ports.Value.Trap, Dashboard @Ports.Value.Dashboard</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
<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>
|
||||
|
||||
@code {
|
||||
private readonly object _resetModel = new();
|
||||
private IReadOnlyDictionary<string, string> _errors = new Dictionary<string, string>();
|
||||
private bool _hasOverrides;
|
||||
private bool _generalOverrides;
|
||||
|
||||
[SupplyParameterFromForm(FormName = "settings")] private SettingsModel? Model { get; set; }
|
||||
|
||||
@@ -122,16 +127,14 @@ else if (Saved == "reset")
|
||||
{
|
||||
Model ??= CurrentValues();
|
||||
_hasOverrides = await Store.HasOverridesAsync();
|
||||
_generalOverrides = await Store.HasOverridesAsync(SettingKeys.General.ToArray());
|
||||
}
|
||||
|
||||
private async Task Save()
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(new RuntimeSettingsInput(
|
||||
Model!.TrapPaths,
|
||||
Model.MaxConnections,
|
||||
Model!.MaxConnections,
|
||||
Model.MaxConnectionsPerIp,
|
||||
Model.MaxHoldDuration,
|
||||
Model.ExtraKnownHosts,
|
||||
Model.RetentionDays,
|
||||
Model.IgnorePrivateNetworks));
|
||||
|
||||
@@ -142,24 +145,20 @@ else if (Saved == "reset")
|
||||
}
|
||||
|
||||
await Store.SaveAsync(result.Settings);
|
||||
Navigation.NavigateTo("/settings?saved=1");
|
||||
Navigation.NavigateTo("/settings?saved=1#connections");
|
||||
}
|
||||
|
||||
private async Task Reset()
|
||||
{
|
||||
await Store.ResetAsync();
|
||||
Navigation.NavigateTo("/settings?saved=reset");
|
||||
Navigation.NavigateTo("/settings?saved=reset#system");
|
||||
}
|
||||
|
||||
private SettingsModel CurrentValues()
|
||||
{
|
||||
var core = Core.CurrentValue;
|
||||
var http = Http.CurrentValue;
|
||||
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),
|
||||
MaxConnectionsPerIp = core.MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
|
||||
RetentionDays = Retention.CurrentValue.Days.ToString(CultureInfo.InvariantCulture),
|
||||
@@ -167,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 NavigationManager Navigation
|
||||
|
||||
<section class="card form">
|
||||
<h2>Daten</h2>
|
||||
|
||||
<SettingsSection Id="data" Title="Daten" Description="Gespeicherte Fänge. Einstellungen und GeoIP-Dateien bleiben beim Löschen erhalten.">
|
||||
@if (Deleted is { } deleted)
|
||||
{
|
||||
<div class="banner ok">@deleted.ToString("N0") @(deleted == 1 ? "Fang" : "Fänge") gelöscht.</div>
|
||||
<Notice>@deleted.ToString("N0") @(deleted == 1 ? "Fang" : "Fänge") gelöscht.</Notice>
|
||||
}
|
||||
|
||||
<table>
|
||||
<tbody>
|
||||
<tr><th>Fänge</th><td>@_stats?.Count.ToString("N0")</td></tr>
|
||||
<tr><th>Ältester Fang</th><td>@(_stats?.Oldest?.ToLocalTime().ToString("dd.MM.yyyy HH:mm") ?? "–")</td></tr>
|
||||
<tr><th>Größe der Datenbank</th><td>@Formatting.Bytes(_stats?.DatabaseBytes)</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="muted">Einstellungen und GeoIP-Dateien bleiben beim Löschen erhalten.</p>
|
||||
<div class="s-body">
|
||||
<div class="stat-row">
|
||||
<div class="stat"><span class="stat-label">Fänge</span><span class="stat-value">@(_stats?.Count.ToString("N0") ?? "–")</span></div>
|
||||
<div class="stat"><span class="stat-label">Ältester Fang</span><span class="stat-value">@(_stats?.Oldest?.ToLocalTime().ToString("dd.MM.yyyy") ?? "–")</span></div>
|
||||
<div class="stat"><span class="stat-label">Datenbank</span><span class="stat-value">@Formatting.Bytes(_stats?.DatabaseBytes)</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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">
|
||||
<div class="danger-box">
|
||||
<h3>Gefahrenzone</h3>
|
||||
|
||||
<EditForm Model="DeletePrivate" FormName="delete-private" OnSubmit="DeletePrivateAsync" action="/settings#data" class="action-row">
|
||||
<div class="action-text">
|
||||
<strong>Fänge aus privaten Netzen löschen</strong>
|
||||
<span class="muted">Loopback, 10/8, 172.16/12, 192.168/16, Link-Local und ULA, etwa eigene Testaufrufe.</span>
|
||||
@if (_errors.TryGetValue(nameof(DeletePrivateModel.Confirmed), out var privateError))
|
||||
{
|
||||
<span class="field-error">@privateError</span>
|
||||
}
|
||||
</div>
|
||||
<div class="action-controls">
|
||||
<label class="inline-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>
|
||||
<button type="submit" class="secondary">Private löschen</button>
|
||||
</div>
|
||||
</EditForm>
|
||||
|
||||
<EditForm Model="DeleteAll" FormName="delete-all" OnSubmit="DeleteAllAsync" action="/settings" class="danger-zone">
|
||||
<h3>Alle Fänge löschen</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" />
|
||||
<FieldError Errors="_errors" Field="@nameof(DeleteAllModel.Confirmation)" />
|
||||
<div class="actions">
|
||||
<button type="submit" class="danger">Alle Fänge löschen</button>
|
||||
<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>
|
||||
</section>
|
||||
</div>
|
||||
</SettingsSection>
|
||||
|
||||
@code {
|
||||
private const string ConfirmationWord = "LÖSCHEN";
|
||||
@@ -91,6 +102,6 @@
|
||||
await Maintenance.VacuumAsync();
|
||||
}
|
||||
|
||||
Navigation.NavigateTo($"/settings?deleted={deleted}");
|
||||
Navigation.NavigateTo($"/settings?deleted={deleted}#data");
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,10 @@
|
||||
<EmbeddedResource Include="Components\Pages\Dashboard\world-map.json" LogicalName="Flypaper.Web.world-map.json" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ModelContextProtocol.AspNetCore" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Flypaper.GeoIp\Flypaper.GeoIp.csproj" />
|
||||
<ProjectReference Include="..\Flypaper.Http\Flypaper.Http.csproj" />
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
using System.ComponentModel;
|
||||
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("ISO 3166-1 alpha-2 country code, e.g. CN.")] 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: ips, countries, providers, targets or 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,59 @@
|
||||
using Flypaper.Storage.Settings;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using ModelContextProtocol.Protocol;
|
||||
|
||||
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.";
|
||||
|
||||
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>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
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)));
|
||||
}
|
||||
@@ -6,6 +6,7 @@ using Flypaper.Web;
|
||||
using Flypaper.Web.Auth;
|
||||
using Flypaper.Web.Components;
|
||||
using Flypaper.Web.Health;
|
||||
using Flypaper.Web.Mcp;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
@@ -32,6 +33,8 @@ if (builder.Configuration["Flypaper:DataProtection:KeysPath"] is { Length: > 0 }
|
||||
dataProtection.PersistKeysToFileSystem(new DirectoryInfo(keysPath));
|
||||
}
|
||||
|
||||
builder.Services.AddFlypaperMcp(builder.Configuration);
|
||||
|
||||
builder.Services.Configure<AdminOptions>(builder.Configuration.GetSection(AdminOptions.SectionName));
|
||||
builder.Services.AddSingleton<AdminAuthenticator>();
|
||||
builder.Services
|
||||
@@ -52,6 +55,7 @@ builder.Services.AddAuthorizationBuilder()
|
||||
var app = builder.Build();
|
||||
|
||||
app.Logger.LogInformation("Flypaper {Version} starting", AppVersion.Current);
|
||||
FlypaperHttpExtensions.WarnAboutRemovedSettings(app.Configuration, app.Logger);
|
||||
await app.Services.MigrateFlypaperDatabaseAsync();
|
||||
|
||||
app.UseFlypaper();
|
||||
@@ -69,6 +73,7 @@ app.UseAntiforgery();
|
||||
app.MapStaticAssets().AllowAnonymous();
|
||||
app.MapAuthEndpoints();
|
||||
app.MapHealthEndpoint();
|
||||
app.MapFlypaperMcp();
|
||||
app.MapRazorComponents<App>();
|
||||
|
||||
await app.RunAsync();
|
||||
|
||||
@@ -23,24 +23,7 @@
|
||||
"MaxConnectionsPerIp": 10,
|
||||
"MaxHoldDuration": "01:00:00",
|
||||
"Http": {
|
||||
"KnownHosts": [],
|
||||
"TrustedProxies": [],
|
||||
"TrapPaths": [
|
||||
"/.env",
|
||||
"/.env.*",
|
||||
"/.git/*",
|
||||
"/.aws/*",
|
||||
"/.DS_Store",
|
||||
"/wp-login.php",
|
||||
"/wp-admin/*",
|
||||
"/xmlrpc.php",
|
||||
"/phpmyadmin/*",
|
||||
"/vendor/phpunit/*",
|
||||
"/server-status",
|
||||
"/actuator/*",
|
||||
"/cgi-bin/*",
|
||||
"/boaform/*"
|
||||
]
|
||||
"TrustedProxies": []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,21 +47,6 @@ h1:focus {
|
||||
padding: 24px 16px 48px;
|
||||
}
|
||||
|
||||
.top {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.top h1 {
|
||||
margin: 0;
|
||||
font-size: 22px;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0 0 12px;
|
||||
font-size: 15px;
|
||||
@@ -73,7 +58,7 @@ h2 {
|
||||
|
||||
.metrics {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
|
||||
grid-template-columns: repeat(2, minmax(0, 1.4fr)) repeat(3, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
@@ -82,35 +67,171 @@ h2 {
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 14px 16px;
|
||||
border-radius: 10px;
|
||||
padding: 16px 18px;
|
||||
}
|
||||
|
||||
.metric {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.metric .label {
|
||||
display: block;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.metric .value {
|
||||
margin-top: 4px;
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.metric .sub {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.metric .value {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
font-size: 24px;
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
.metric-hero .value {
|
||||
font-size: 32px;
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.tops {
|
||||
.metric-hero.live {
|
||||
border-color: color-mix(in srgb, var(--accent) 55%, var(--border));
|
||||
background: color-mix(in srgb, var(--accent) 8%, var(--surface));
|
||||
}
|
||||
|
||||
.metric-hero.live .value {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.metric-hero.live .label::before,
|
||||
.live-dot {
|
||||
content: "";
|
||||
display: inline-block;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
margin-right: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--accent);
|
||||
vertical-align: 1px;
|
||||
animation: pulse 2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.live-dot {
|
||||
background: var(--ok);
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
50% {
|
||||
opacity: 0.35;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.metric-hero.live .label::before,
|
||||
.live-dot {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
.card-head {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px 16px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.card-head h2 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.card-head .hint {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.onboarding {
|
||||
border-style: dashed;
|
||||
}
|
||||
|
||||
.onboarding p {
|
||||
margin: 0 0 12px;
|
||||
}
|
||||
|
||||
.onboarding ol {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 16px;
|
||||
margin-bottom: 16px;
|
||||
gap: 8px;
|
||||
margin: 0;
|
||||
padding-left: 20px;
|
||||
}
|
||||
|
||||
.tops > * {
|
||||
code {
|
||||
padding: 1px 5px;
|
||||
border-radius: 4px;
|
||||
background: var(--bg);
|
||||
font: 12.5px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
}
|
||||
|
||||
.origin {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.8fr) minmax(0, 1fr);
|
||||
gap: 16px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.origin > * {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.tops-card h2 {
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
margin: 0 -4px 8px;
|
||||
padding: 0 4px;
|
||||
overflow-x: auto;
|
||||
border-bottom: 1px solid var(--border);
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.tabs button[role="tab"] {
|
||||
flex: none;
|
||||
margin-bottom: -1px;
|
||||
padding: 7px 12px;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
border-radius: 6px 6px 0 0;
|
||||
background: none;
|
||||
color: var(--muted);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.tabs button[role="tab"]:hover {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.tabs button[role="tab"][aria-selected="true"] {
|
||||
border-bottom-color: var(--accent);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.tabs button[role="tab"]:focus-visible,
|
||||
[role="tabpanel"]:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.top-table {
|
||||
table-layout: fixed;
|
||||
}
|
||||
@@ -289,7 +410,7 @@ tr[data-expand] {
|
||||
}
|
||||
|
||||
tr[data-expand]:hover td {
|
||||
background: color-mix(in srgb, var(--text) 4%, transparent);
|
||||
background-color: color-mix(in srgb, var(--text) 4%, transparent);
|
||||
}
|
||||
|
||||
tr[data-expand]:focus-visible {
|
||||
@@ -298,7 +419,7 @@ tr[data-expand]:focus-visible {
|
||||
}
|
||||
|
||||
tr[data-expand].open td {
|
||||
background: color-mix(in srgb, var(--accent) 7%, transparent);
|
||||
background-color: color-mix(in srgb, var(--accent) 7%, transparent);
|
||||
}
|
||||
|
||||
tr.open .clip {
|
||||
@@ -343,13 +464,15 @@ tr.open .clip {
|
||||
.nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
margin-bottom: 20px;
|
||||
gap: 4px;
|
||||
margin-bottom: 28px;
|
||||
padding-bottom: 12px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.nav a {
|
||||
padding: 6px 12px;
|
||||
border-radius: 6px;
|
||||
color: var(--muted);
|
||||
text-decoration: none;
|
||||
font-weight: 500;
|
||||
@@ -360,6 +483,31 @@ tr.open .clip {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.nav a.active {
|
||||
background: var(--surface);
|
||||
box-shadow: inset 0 -2px 0 var(--accent);
|
||||
}
|
||||
|
||||
.nav .brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-right: 16px;
|
||||
padding-left: 0;
|
||||
color: var(--text);
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.brand-mark {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: 4px;
|
||||
background: var(--accent);
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 25%, transparent);
|
||||
}
|
||||
|
||||
.nav .logout {
|
||||
margin-left: auto;
|
||||
}
|
||||
@@ -382,7 +530,7 @@ tr.open .clip {
|
||||
gap: 0 16px;
|
||||
}
|
||||
|
||||
input,
|
||||
input:not([type="radio"], [type="checkbox"]),
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
@@ -393,12 +541,18 @@ textarea {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
input:focus,
|
||||
input:not([type="radio"], [type="checkbox"]):focus,
|
||||
textarea:focus {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
input[type="radio"]:focus-visible,
|
||||
input[type="checkbox"]:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
@@ -482,10 +636,6 @@ tbody th {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.top h1 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.world-map {
|
||||
display: block;
|
||||
width: 100%;
|
||||
@@ -553,13 +703,41 @@ tbody th {
|
||||
.map-legend {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 4px;
|
||||
margin-top: 8px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.map-legend .level-0 {
|
||||
margin-right: 6px;
|
||||
}
|
||||
|
||||
.map-wrap {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.map-empty {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
bottom: 12%;
|
||||
transform: translateX(-50%);
|
||||
margin: 0;
|
||||
padding: 8px 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: var(--surface);
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
td.bar {
|
||||
background-image: linear-gradient(to right, color-mix(in srgb, var(--accent) 70%, transparent) var(--share), transparent var(--share));
|
||||
background-repeat: no-repeat;
|
||||
background-size: 100% 3px;
|
||||
background-position: 0 calc(100% - 3px);
|
||||
}
|
||||
|
||||
.map-legend .swatch {
|
||||
width: 18px;
|
||||
height: 10px;
|
||||
@@ -586,42 +764,606 @@ tr.open .detail {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
.check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.check input {
|
||||
width: auto;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
.danger-zone {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
margin-top: 16px;
|
||||
padding-top: 16px;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.danger-zone h3 {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.danger-zone p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
button.danger {
|
||||
background: var(--bad);
|
||||
}
|
||||
|
||||
@media (max-width: 860px) {
|
||||
.tops {
|
||||
@media (max-width: 1099px) {
|
||||
.metrics {
|
||||
grid-template-columns: repeat(6, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.metric {
|
||||
grid-column: span 2;
|
||||
}
|
||||
|
||||
.metric-hero {
|
||||
grid-column: span 3;
|
||||
}
|
||||
|
||||
.origin {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 599px) {
|
||||
.metrics {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.metric,
|
||||
.metric-hero {
|
||||
grid-column: span 1;
|
||||
}
|
||||
|
||||
.metric:last-child {
|
||||
grid-column: span 2;
|
||||
}
|
||||
|
||||
.metric-hero .value {
|
||||
font-size: 26px;
|
||||
}
|
||||
|
||||
.nav .brand {
|
||||
margin-right: 4px;
|
||||
font-size: 0;
|
||||
}
|
||||
|
||||
.map-empty {
|
||||
position: static;
|
||||
transform: none;
|
||||
margin-top: 8px;
|
||||
white-space: normal;
|
||||
border-radius: 8px;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
select {
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.page-head {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.page-head h1 {
|
||||
margin: 0 0 6px;
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.page-head p {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.settings-layout {
|
||||
display: grid;
|
||||
grid-template-columns: 200px minmax(0, 1fr);
|
||||
gap: 32px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.settings-nav {
|
||||
position: sticky;
|
||||
top: 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.settings-nav a {
|
||||
padding: 7px 12px;
|
||||
border-radius: 6px;
|
||||
color: var(--muted);
|
||||
text-decoration: none;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.settings-nav a:hover,
|
||||
.settings-nav a.active {
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.settings-nav a.active {
|
||||
box-shadow: inset 2px 0 0 var(--accent);
|
||||
}
|
||||
|
||||
.settings-sections {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 24px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.s-section {
|
||||
scroll-margin-top: 24px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
.s-head {
|
||||
padding: 20px 24px 0;
|
||||
}
|
||||
|
||||
.s-head h2 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
}
|
||||
|
||||
.s-head p {
|
||||
max-width: 60ch;
|
||||
margin: 6px 0 0;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.s-badge {
|
||||
padding: 2px 8px;
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: 999px;
|
||||
color: var(--accent);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
.s-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
padding: 20px 24px 24px;
|
||||
}
|
||||
|
||||
.s-foot {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 12px;
|
||||
padding: 14px 24px;
|
||||
border-top: 1px solid var(--border);
|
||||
background: color-mix(in srgb, var(--bg) 45%, var(--surface));
|
||||
border-radius: 0 0 10px 10px;
|
||||
}
|
||||
|
||||
.s-foot > form:first-child:not(:only-child) {
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.s-foot-text {
|
||||
margin-right: auto;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.s-section > .notice {
|
||||
margin: 16px 24px 0;
|
||||
}
|
||||
|
||||
.notice {
|
||||
padding: 10px 14px;
|
||||
border: 1px solid color-mix(in srgb, var(--ok) 45%, var(--border));
|
||||
border-left: 3px solid var(--ok);
|
||||
border-radius: 6px;
|
||||
background: color-mix(in srgb, var(--ok) 8%, var(--surface));
|
||||
}
|
||||
|
||||
.notice.bad {
|
||||
border-color: color-mix(in srgb, var(--bad) 45%, var(--border));
|
||||
border-left-color: var(--bad);
|
||||
background: color-mix(in srgb, var(--bad) 8%, var(--surface));
|
||||
}
|
||||
|
||||
.fields {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
|
||||
gap: 18px 20px;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.field label,
|
||||
.choices legend {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.field-control {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.field-control.has-unit input {
|
||||
padding-right: 52px;
|
||||
}
|
||||
|
||||
.field-unit {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 12px;
|
||||
transform: translateY(-50%);
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.field-hint,
|
||||
.field-error {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.field-hint {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.field-error {
|
||||
color: var(--bad);
|
||||
}
|
||||
|
||||
.field:has(.field-error) input {
|
||||
border-color: var(--bad);
|
||||
}
|
||||
|
||||
.settings input {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.choices {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.choices legend {
|
||||
margin-bottom: 8px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.choice-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.choice {
|
||||
position: relative;
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
padding: 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--bg);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.choice:hover {
|
||||
border-color: color-mix(in srgb, var(--accent) 50%, var(--border));
|
||||
}
|
||||
|
||||
.choice:has(input:checked) {
|
||||
border-color: var(--accent);
|
||||
background: color-mix(in srgb, var(--accent) 8%, var(--bg));
|
||||
}
|
||||
|
||||
.choice input {
|
||||
flex: none;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin: 2px 0 0;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
.choice-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.choice-body span {
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.estimate {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 6px 12px;
|
||||
padding: 12px 14px;
|
||||
border-radius: 8px;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.estimate-value {
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.estimate-value strong {
|
||||
color: var(--accent);
|
||||
font-size: 20px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.switch-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.switch-row > span {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.switch-row .muted {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
input.switch {
|
||||
flex: none;
|
||||
position: relative;
|
||||
width: 38px;
|
||||
height: 22px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: var(--bg);
|
||||
appearance: none;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
input.switch::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
left: 2px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border-radius: 50%;
|
||||
background: var(--muted);
|
||||
transition: transform 0.15s, background 0.15s;
|
||||
}
|
||||
|
||||
input.switch:checked {
|
||||
border-color: var(--accent);
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
input.switch:checked::after {
|
||||
background: #fff;
|
||||
transform: translateX(16px);
|
||||
}
|
||||
|
||||
.stat-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.stat {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding: 12px 14px;
|
||||
border-radius: 8px;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.danger-box {
|
||||
margin: 0 24px 24px;
|
||||
border: 1px solid color-mix(in srgb, var(--bad) 40%, var(--border));
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.danger-box h3 {
|
||||
margin: 0;
|
||||
padding: 10px 16px;
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--bad) 25%, var(--border));
|
||||
color: var(--bad);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.action-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px 20px;
|
||||
padding: 14px 16px;
|
||||
}
|
||||
|
||||
.action-row + .action-row {
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.action-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
min-width: 0;
|
||||
flex: 1 1 280px;
|
||||
}
|
||||
|
||||
.action-text .muted {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.action-controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.action-controls input[type="text"],
|
||||
.action-controls input:not([type]) {
|
||||
width: 130px;
|
||||
}
|
||||
|
||||
.inline-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.inline-check input {
|
||||
width: auto;
|
||||
accent-color: var(--bad);
|
||||
}
|
||||
|
||||
.inline-field {
|
||||
display: flex;
|
||||
flex: 1 1 240px;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.kv {
|
||||
display: grid;
|
||||
gap: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.kv > div {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(140px, 220px) minmax(0, 1fr);
|
||||
gap: 12px;
|
||||
padding: 9px 0;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.kv > div:last-child {
|
||||
border-bottom: 0;
|
||||
}
|
||||
|
||||
.kv dt {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.kv dd {
|
||||
margin: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.s-table th {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.empty {
|
||||
margin: 0;
|
||||
padding: 14px;
|
||||
border: 1px dashed var(--border);
|
||||
border-radius: 8px;
|
||||
color: var(--muted);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.token {
|
||||
display: block;
|
||||
margin-top: 8px;
|
||||
padding: 8px 10px;
|
||||
border-radius: 6px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
overflow-wrap: anywhere;
|
||||
user-select: all;
|
||||
}
|
||||
|
||||
button.ghost {
|
||||
padding: 8px 12px;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
button.ghost:hover:not(:disabled) {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
button.danger-text {
|
||||
color: var(--bad);
|
||||
}
|
||||
|
||||
@media (max-width: 899px) {
|
||||
.settings-layout {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.settings-nav {
|
||||
position: static;
|
||||
flex-direction: row;
|
||||
gap: 6px;
|
||||
overflow-x: auto;
|
||||
padding-bottom: 4px;
|
||||
}
|
||||
|
||||
.settings-nav a {
|
||||
flex: none;
|
||||
border: 1px solid var(--border);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.settings-nav a.active {
|
||||
border-color: var(--accent);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.s-head,
|
||||
.s-body {
|
||||
padding-left: 16px;
|
||||
padding-right: 16px;
|
||||
}
|
||||
|
||||
.s-foot {
|
||||
padding-left: 16px;
|
||||
padding-right: 16px;
|
||||
}
|
||||
|
||||
.s-section > .notice {
|
||||
margin-left: 16px;
|
||||
margin-right: 16px;
|
||||
}
|
||||
|
||||
.danger-box {
|
||||
margin-left: 16px;
|
||||
margin-right: 16px;
|
||||
}
|
||||
|
||||
.kv > div {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 2px;
|
||||
}
|
||||
}
|
||||
@@ -52,3 +52,59 @@
|
||||
|
||||
save(expanded);
|
||||
})();
|
||||
|
||||
(() => {
|
||||
const storageKey = "flypaper.tab";
|
||||
const tabs = [...document.querySelectorAll('[role="tab"]')];
|
||||
if (tabs.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const select = (tab, focus) => {
|
||||
for (const other of tabs) {
|
||||
const selected = other === tab;
|
||||
other.setAttribute("aria-selected", String(selected));
|
||||
other.tabIndex = selected ? 0 : -1;
|
||||
document.getElementById(other.getAttribute("aria-controls")).hidden = !selected;
|
||||
}
|
||||
|
||||
if (focus) {
|
||||
tab.focus();
|
||||
}
|
||||
|
||||
try {
|
||||
sessionStorage.setItem(storageKey, tab.id);
|
||||
} catch {
|
||||
}
|
||||
};
|
||||
|
||||
let stored = null;
|
||||
try {
|
||||
stored = sessionStorage.getItem(storageKey);
|
||||
} catch {
|
||||
}
|
||||
|
||||
const initial = tabs.find(tab => tab.id === stored);
|
||||
if (initial) {
|
||||
select(initial, false);
|
||||
}
|
||||
|
||||
for (const tab of tabs) {
|
||||
tab.addEventListener("click", () => select(tab, false));
|
||||
|
||||
tab.addEventListener("keydown", event => {
|
||||
const index = tabs.indexOf(tab);
|
||||
const target = {
|
||||
ArrowRight: tabs[(index + 1) % tabs.length],
|
||||
ArrowLeft: tabs[(index - 1 + tabs.length) % tabs.length],
|
||||
Home: tabs[0],
|
||||
End: tabs.at(-1)
|
||||
}[event.key];
|
||||
|
||||
if (target) {
|
||||
event.preventDefault();
|
||||
select(target, true);
|
||||
}
|
||||
});
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,67 @@
|
||||
(() => {
|
||||
const links = new Map([...document.querySelectorAll(".settings-nav a")].map(link => [link.hash.slice(1), link]));
|
||||
if (links.size === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const lastId = [...links.keys()].at(-1);
|
||||
const atBottom = () => window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 4;
|
||||
const activate = id => {
|
||||
links.forEach(link => link.classList.toggle("active", link === links.get(id)));
|
||||
};
|
||||
|
||||
const observer = new IntersectionObserver(entries => {
|
||||
if (atBottom()) {
|
||||
activate(lastId);
|
||||
return;
|
||||
}
|
||||
|
||||
const visible = entries.find(entry => entry.isIntersecting);
|
||||
if (visible) {
|
||||
activate(visible.target.id);
|
||||
}
|
||||
}, { rootMargin: "-20% 0px -70% 0px" });
|
||||
|
||||
links.forEach((link, id) => {
|
||||
const section = document.getElementById(id);
|
||||
if (section) {
|
||||
observer.observe(section);
|
||||
}
|
||||
|
||||
link.addEventListener("click", () => activate(id));
|
||||
});
|
||||
|
||||
window.addEventListener("scroll", () => {
|
||||
if (atBottom()) {
|
||||
activate(lastId);
|
||||
}
|
||||
}, { passive: true });
|
||||
|
||||
if (location.hash && links.has(location.hash.slice(1))) {
|
||||
activate(location.hash.slice(1));
|
||||
}
|
||||
})();
|
||||
|
||||
(() => {
|
||||
const value = id => Number.parseInt(document.getElementById(id)?.value ?? "", 10);
|
||||
const output = document.getElementById("drip-bandwidth");
|
||||
if (!output) {
|
||||
return;
|
||||
}
|
||||
|
||||
const update = () => {
|
||||
const minDelay = value("drip-min-delay");
|
||||
const maxDelay = value("drip-max-delay");
|
||||
const minChunk = value("drip-min-chunk");
|
||||
const maxChunk = value("drip-max-chunk");
|
||||
const averageDelay = (minDelay + maxDelay) / 2000;
|
||||
const bytesPerSecond = (minChunk + maxChunk) / 2 / averageDelay;
|
||||
output.textContent = Number.isFinite(bytesPerSecond) && bytesPerSecond > 0
|
||||
? bytesPerSecond.toLocaleString("de-DE", { maximumFractionDigits: bytesPerSecond < 10 ? 1 : 0 })
|
||||
: "–";
|
||||
};
|
||||
|
||||
for (const input of document.querySelectorAll("[data-bandwidth-input]")) {
|
||||
input.addEventListener("input", update);
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,73 @@
|
||||
using Flypaper.Core.Settings;
|
||||
using Flypaper.Core.Strategies;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Core;
|
||||
|
||||
public sealed class HoldMethodParserTests
|
||||
{
|
||||
private static readonly HoldMethodInput Valid = new("Alternating", "50", "1000", "1", "64", "01:00:00");
|
||||
|
||||
[Fact]
|
||||
public void Parses_valid_input()
|
||||
{
|
||||
var settings = RuntimeSettingsParser.ParseHoldMethod(Valid).Settings.ShouldNotBeNull();
|
||||
|
||||
settings.Content.ShouldBe(DripContent.Alternating);
|
||||
settings.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(50));
|
||||
settings.MaxDelay.ShouldBe(TimeSpan.FromSeconds(1));
|
||||
settings.MinChunkSize.ShouldBe(1);
|
||||
settings.MaxChunkSize.ShouldBe(64);
|
||||
settings.MaxHoldDuration.ShouldBe(TimeSpan.FromHours(1));
|
||||
settings.ToConfiguration().Keys.ShouldBe(SettingKeys.HoldMethod, ignoreOrder: true);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("html", DripContent.Html)]
|
||||
[InlineData("Text", DripContent.Text)]
|
||||
public void Accepts_content_case_insensitively(string value, DripContent expected) =>
|
||||
RuntimeSettingsParser.ParseHoldMethod(Valid with { Content = value }).Settings.ShouldNotBeNull().Content.ShouldBe(expected);
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("fake-env")]
|
||||
[InlineData("7")]
|
||||
public void Rejects_unknown_content(string value) =>
|
||||
RuntimeSettingsParser.ParseHoldMethod(Valid with { Content = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.Content)]);
|
||||
|
||||
[Theory]
|
||||
[InlineData("9", "1000")]
|
||||
[InlineData("50", "30001")]
|
||||
[InlineData("x", "1000")]
|
||||
public void Rejects_delays_out_of_range(string min, string max) =>
|
||||
RuntimeSettingsParser.ParseHoldMethod(Valid with { MinDelayMs = min, MaxDelayMs = max }).Settings.ShouldBeNull();
|
||||
|
||||
[Theory]
|
||||
[InlineData("0", "64")]
|
||||
[InlineData("1", "4097")]
|
||||
public void Rejects_chunk_sizes_out_of_range(string min, string max) =>
|
||||
RuntimeSettingsParser.ParseHoldMethod(Valid with { MinChunkSize = min, MaxChunkSize = max }).Settings.ShouldBeNull();
|
||||
|
||||
[Fact]
|
||||
public void Requires_minimum_not_above_maximum()
|
||||
{
|
||||
var errors = RuntimeSettingsParser.ParseHoldMethod(Valid with { MinDelayMs = "2000", MaxDelayMs = "1000", MinChunkSize = "100", MaxChunkSize = "10" }).Errors;
|
||||
|
||||
errors.Keys.ShouldBe([nameof(HoldMethodInput.MaxDelayMs), nameof(HoldMethodInput.MaxChunkSize)], ignoreOrder: true);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("10")]
|
||||
[InlineData("00:00:00")]
|
||||
[InlineData("8.00:00:00")]
|
||||
public void Rejects_invalid_hold_durations(string value) =>
|
||||
RuntimeSettingsParser.ParseHoldMethod(Valid with { MaxHoldDuration = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.MaxHoldDuration)]);
|
||||
|
||||
[Fact]
|
||||
public void Computes_average_bandwidth()
|
||||
{
|
||||
HoldMethodSettings.AverageBytesPerSecond(TimeSpan.FromMilliseconds(50), TimeSpan.FromSeconds(1), 1, 64)
|
||||
.ShouldBe(61.9, tolerance: 0.1);
|
||||
HoldMethodSettings.AverageBytesPerSecond(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), 10, 10).ShouldBe(10);
|
||||
}
|
||||
}
|
||||
@@ -5,27 +5,17 @@ namespace Flypaper.Tests.Core;
|
||||
|
||||
public sealed class RuntimeSettingsParserTests
|
||||
{
|
||||
private static readonly RuntimeSettingsInput Valid = new(
|
||||
"/.env\n/wp-admin/*\r\n /xmlrpc.php \n/.env",
|
||||
"200",
|
||||
"5",
|
||||
"00:30:00",
|
||||
"example.com\n*.example.org",
|
||||
"90",
|
||||
true);
|
||||
private static readonly RuntimeSettingsInput Valid = new("200", "5", "90", true);
|
||||
|
||||
[Fact]
|
||||
public void Parses_valid_input_and_normalizes_lists()
|
||||
public void Parses_valid_input()
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(Valid);
|
||||
|
||||
result.Errors.ShouldBeEmpty();
|
||||
var settings = result.Settings.ShouldNotBeNull();
|
||||
settings.TrapPaths.ShouldBe(["/.env", "/wp-admin/*", "/xmlrpc.php"]);
|
||||
settings.ExtraKnownHosts.ShouldBe(["example.com", "*.example.org"]);
|
||||
settings.MaxConnections.ShouldBe(200);
|
||||
settings.MaxConnectionsPerIp.ShouldBe(5);
|
||||
settings.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(30));
|
||||
settings.RetentionDays.ShouldBe(90);
|
||||
settings.IgnorePrivateNetworks.ShouldBeTrue();
|
||||
}
|
||||
@@ -54,51 +44,6 @@ public sealed class RuntimeSettingsParserTests
|
||||
settings.ToConfiguration()[SettingKeys.IgnorePrivateNetworks].ShouldBe("false");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Accepts_empty_lists()
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(Valid with { TrapPaths = "", ExtraKnownHosts = null });
|
||||
|
||||
result.Settings.ShouldNotBeNull().TrapPaths.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("env")]
|
||||
[InlineData("/with space")]
|
||||
[InlineData("/a*b")]
|
||||
public void Rejects_invalid_trap_paths(string path)
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(Valid with { TrapPaths = $"/ok\n{path}" });
|
||||
|
||||
result.Settings.ShouldBeNull();
|
||||
result.Errors.Keys.ShouldBe([nameof(RuntimeSettingsInput.TrapPaths)]);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("https://example.com")]
|
||||
[InlineData("example.com/path")]
|
||||
[InlineData("example.com:8080")]
|
||||
[InlineData("-bad.com")]
|
||||
public void Rejects_invalid_hosts(string host)
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(Valid with { ExtraKnownHosts = host });
|
||||
|
||||
result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.ExtraKnownHosts));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("10")]
|
||||
[InlineData("abc")]
|
||||
[InlineData("")]
|
||||
[InlineData("00:00:00")]
|
||||
[InlineData("8.00:00:00")]
|
||||
public void Rejects_invalid_hold_durations(string value)
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(Valid with { MaxHoldDuration = value });
|
||||
|
||||
result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.MaxHoldDuration));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("0")]
|
||||
[InlineData("-3")]
|
||||
@@ -122,19 +67,11 @@ public sealed class RuntimeSettingsParserTests
|
||||
result.Errors.Keys.ShouldBe([nameof(RuntimeSettingsInput.MaxConnectionsPerIp)]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rejects_hold_duration_out_of_range()
|
||||
{
|
||||
var result = RuntimeSettingsParser.Parse(Valid with { MaxHoldDuration = "00:00:00.5" });
|
||||
|
||||
result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.MaxHoldDuration));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Exposes_only_whitelisted_configuration_keys()
|
||||
{
|
||||
var keys = RuntimeSettingsParser.Parse(Valid).Settings.ShouldNotBeNull().ToConfiguration().Keys;
|
||||
|
||||
keys.ShouldBe(SettingKeys.All, ignoreOrder: true);
|
||||
keys.ShouldBe(SettingKeys.General, ignoreOrder: true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Core.Runtime;
|
||||
using Flypaper.Core.Strategies;
|
||||
using Flypaper.Tests.Fakes;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Core;
|
||||
|
||||
public sealed class StrategySelectionTests
|
||||
{
|
||||
private static readonly TrapContext Http =
|
||||
new(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow));
|
||||
|
||||
[Theory]
|
||||
[InlineData(DripContent.Html, "html-drip")]
|
||||
[InlineData(DripContent.Text, "text-drip")]
|
||||
public void Selects_the_configured_content(DripContent content, string expected) =>
|
||||
Selector(content).Select(Http).ShouldNotBeNull().Name.ShouldBe(expected);
|
||||
|
||||
[Fact]
|
||||
public void Alternating_picks_both_strategies()
|
||||
{
|
||||
var selector = Selector(DripContent.Alternating);
|
||||
|
||||
var names = Enumerable.Range(0, 50).Select(_ => selector.Select(Http)!.Name).Distinct().ToList();
|
||||
|
||||
names.ShouldBe(["html-drip", "text-drip"], ignoreOrder: true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Returns_nothing_for_unsupported_protocols()
|
||||
{
|
||||
var ssh = Http with { Session = Http.Session with { Protocol = TrapProtocol.Ssh } };
|
||||
|
||||
Selector(DripContent.Html).Select(ssh).ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Strategies_describe_themselves_with_their_parameters()
|
||||
{
|
||||
var options = TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(100), MaxDelay = TimeSpan.FromMilliseconds(250), MinChunkSize = 2, MaxChunkSize = 8 });
|
||||
var text = new TextDripStrategy(options, new SeededRandomSource(1), TimeProvider.System);
|
||||
|
||||
text.Describe().ShouldBe("text-drip 100-250ms 2-8B");
|
||||
text.MediaType.ShouldStartWith("text/plain");
|
||||
new HtmlDripStrategy(options, new SeededRandomSource(1), TimeProvider.System).MediaType.ShouldStartWith("text/html");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Text_strategy_drips_plain_text()
|
||||
{
|
||||
var strategy = new TextDripStrategy(
|
||||
TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(2), MinChunkSize = 32, MaxChunkSize = 64 }),
|
||||
new SeededRandomSource(3),
|
||||
TimeProvider.System);
|
||||
var channel = new FakeTrapChannel();
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
|
||||
|
||||
await Should.ThrowAsync<OperationCanceledException>(() => strategy.RunAsync(channel, cts.Token));
|
||||
|
||||
var text = Encoding.UTF8.GetString(channel.Writes.SelectMany(w => w).ToArray());
|
||||
text.Length.ShouldBeGreaterThan(200);
|
||||
text.ShouldNotContain("<");
|
||||
text.ShouldContain("\n");
|
||||
}
|
||||
|
||||
private static ConfiguredStrategySelector Selector(DripContent content)
|
||||
{
|
||||
var options = TestOptions.Monitor(new DripOptions { Content = content });
|
||||
var random = new SeededRandomSource(11);
|
||||
return new ConfiguredStrategySelector(
|
||||
[new HtmlDripStrategy(options, random, TimeProvider.System), new TextDripStrategy(options, random, TimeProvider.System)],
|
||||
options,
|
||||
random);
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ public sealed class TrapRunnerTests
|
||||
|
||||
var outcome = await CreateRunner(TimeSpan.FromSeconds(1)).RunAsync(
|
||||
Context(),
|
||||
_ =>
|
||||
(_, _) =>
|
||||
{
|
||||
opened = true;
|
||||
return ValueTask.FromResult<ITrapChannel>(_channel);
|
||||
@@ -59,7 +59,7 @@ public sealed class TrapRunnerTests
|
||||
var outcome = await CreateRunner(TimeSpan.FromMinutes(1)).RunAsync(Context(), Open, cts.Token);
|
||||
|
||||
outcome.ShouldBe(TrapOutcome.ClientAborted);
|
||||
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "html-drip"));
|
||||
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "html-drip 5-20ms 1-64B"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
@@ -111,17 +111,16 @@ public sealed class TrapRunnerTests
|
||||
return lease;
|
||||
}
|
||||
|
||||
private ValueTask<ITrapChannel> Open(CancellationToken ct) => ValueTask.FromResult<ITrapChannel>(_channel);
|
||||
private ValueTask<ITrapChannel> Open(ITarpitStrategy strategy, CancellationToken ct) => ValueTask.FromResult<ITrapChannel>(_channel);
|
||||
|
||||
private TrapRunner CreateRunner(TimeSpan maxHoldDuration, bool ignorePrivateNetworks = true)
|
||||
{
|
||||
var drip = new HtmlDripStrategy(
|
||||
TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(5), MaxDelay = TimeSpan.FromMilliseconds(20) }),
|
||||
new SeededRandomSource(7),
|
||||
TimeProvider.System);
|
||||
var dripOptions = TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(5), MaxDelay = TimeSpan.FromMilliseconds(20) });
|
||||
var random = new SeededRandomSource(7);
|
||||
var drip = new HtmlDripStrategy(dripOptions, random, TimeProvider.System);
|
||||
return new TrapRunner(
|
||||
_governor,
|
||||
new ProtocolStrategySelector([drip]),
|
||||
new ConfiguredStrategySelector([drip], dripOptions, random),
|
||||
_sink,
|
||||
TestOptions.Monitor(new FlypaperOptions { MaxHoldDuration = maxHoldDuration, IgnorePrivateNetworks = ignorePrivateNetworks }),
|
||||
TimeProvider.System,
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Flypaper.Tests.Fakes;
|
||||
|
||||
internal sealed class ListLogger : ILogger
|
||||
{
|
||||
public List<(LogLevel Level, string Message)> Entries { get; } = [];
|
||||
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) =>
|
||||
Entries.Add((logLevel, formatter(state, exception)));
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core;
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Http;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Http;
|
||||
|
||||
public sealed class ContentTypeTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("Html", "text/html; charset=utf-8")]
|
||||
[InlineData("Text", "text/plain; charset=utf-8")]
|
||||
public async Task Trap_answers_with_the_media_type_of_the_selected_strategy(string content, string expected)
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["Flypaper:MaxHoldDuration"] = "00:00:00.100",
|
||||
["Flypaper:Drip:Content"] = content,
|
||||
["Flypaper:Drip:MinDelay"] = "00:00:00.005",
|
||||
["Flypaper:Drip:MaxDelay"] = "00:00:00.010"
|
||||
})
|
||||
.Build();
|
||||
var services = new ServiceCollection()
|
||||
.AddLogging()
|
||||
.AddSingleton(Substitute.For<ITrapEventSink>())
|
||||
.AddFlypaperCore(configuration)
|
||||
.AddFlypaperHttp(configuration)
|
||||
.BuildServiceProvider();
|
||||
|
||||
var app = new ApplicationBuilder(services);
|
||||
app.UseFlypaper();
|
||||
var context = new DefaultHttpContext { RequestServices = services };
|
||||
context.Connection.RemoteIpAddress = IPAddress.Parse("203.0.113.9");
|
||||
context.Connection.LocalPort = 8080;
|
||||
context.Request.Path = "/";
|
||||
|
||||
await app.Build()(context);
|
||||
|
||||
context.Response.StatusCode.ShouldBe(StatusCodes.Status200OK);
|
||||
context.Response.ContentType.ShouldBe(expected);
|
||||
}
|
||||
}
|
||||
@@ -48,8 +48,7 @@ public sealed class HealthProbeTests
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["Flypaper:MaxConnections"] = "0",
|
||||
["Flypaper:Http:KnownHosts:0"] = "dashboard.lan"
|
||||
["Flypaper:MaxConnections"] = "0"
|
||||
})
|
||||
.Build();
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core;
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Http;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -31,39 +32,49 @@ public sealed class PortSeparationTests
|
||||
[Theory]
|
||||
[InlineData("unknown.example", "/")]
|
||||
[InlineData("203.0.113.7", "/settings")]
|
||||
[InlineData("example.com", "/")]
|
||||
[InlineData("example.com", "/.env")]
|
||||
public async Task Trap_port_traps_unknown_hosts_and_trap_paths(string host, string path)
|
||||
{
|
||||
var (reachedApp, status) = await SendAsync(TrapPort, host, path);
|
||||
|
||||
reachedApp.ShouldBeFalse();
|
||||
status.ShouldBe(StatusCodes.Status404NotFound);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/")]
|
||||
[InlineData("/settings")]
|
||||
[InlineData("/login")]
|
||||
public async Task Trap_port_answers_other_paths_of_known_hosts_with_plain_404(string path)
|
||||
[InlineData("example.com", "/login")]
|
||||
[InlineData("", "/wp-login.php")]
|
||||
[InlineData("unknown.example", "/mcp")]
|
||||
[InlineData("203.0.113.7", "/health")]
|
||||
public async Task Trap_port_catches_every_host_and_path(string host, string path)
|
||||
{
|
||||
var sink = Substitute.For<ITrapEventSink>();
|
||||
|
||||
var (reachedApp, status) = await SendAsync(TrapPort, "example.com", path, sink);
|
||||
var (reachedApp, status) = await SendAsync(TrapPort, host, path, sink);
|
||||
|
||||
reachedApp.ShouldBeFalse();
|
||||
status.ShouldBe(StatusCodes.Status404NotFound);
|
||||
sink.DidNotReceiveWithAnyArgs().Publish(default!);
|
||||
sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Outcome == TrapOutcome.Rejected));
|
||||
}
|
||||
|
||||
private static async Task<(bool ReachedApp, int Status)> SendAsync(int localPort, string host, string path, ITrapEventSink? sink = null)
|
||||
[Fact]
|
||||
public async Task Removed_settings_change_nothing()
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
var (reachedApp, _) = await SendAsync(
|
||||
TrapPort,
|
||||
"example.com",
|
||||
"/",
|
||||
extraSettings: new Dictionary<string, string?>
|
||||
{
|
||||
["Flypaper:MaxConnections"] = "0",
|
||||
["Flypaper:Http:KnownHosts:0"] = "example.com",
|
||||
["Flypaper:Http:TrapPaths:0"] = "/.env"
|
||||
})
|
||||
});
|
||||
|
||||
reachedApp.ShouldBeFalse();
|
||||
}
|
||||
|
||||
private static async Task<(bool ReachedApp, int Status)> SendAsync(
|
||||
int localPort,
|
||||
string host,
|
||||
string path,
|
||||
ITrapEventSink? sink = null,
|
||||
Dictionary<string, string?>? extraSettings = null)
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?> { ["Flypaper:MaxConnections"] = "0" })
|
||||
.AddInMemoryCollection(extraSettings ?? [])
|
||||
.Build();
|
||||
|
||||
var services = new ServiceCollection()
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
using Flypaper.Http;
|
||||
using Flypaper.Tests.Fakes;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Http;
|
||||
|
||||
public sealed class RemovedSettingsTests
|
||||
{
|
||||
[Fact]
|
||||
public void Warns_about_each_removed_setting_that_is_still_set()
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["Flypaper:Http:KnownHosts:0"] = "example.com",
|
||||
["Flypaper:Http:TrapPaths:0"] = "/.env",
|
||||
["Flypaper:Http:TrustedProxies:0"] = "172.19.0.0/16"
|
||||
})
|
||||
.Build();
|
||||
var logger = new ListLogger();
|
||||
|
||||
FlypaperHttpExtensions.WarnAboutRemovedSettings(configuration, logger);
|
||||
|
||||
logger.Entries.Count.ShouldBe(2);
|
||||
logger.Entries.ShouldAllBe(e => e.Level == LogLevel.Warning);
|
||||
logger.Entries.ShouldContain(e => e.Message.Contains("Flypaper__Http__KnownHosts"));
|
||||
logger.Entries.ShouldContain(e => e.Message.Contains("Flypaper__Http__TrapPaths"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Stays_silent_without_removed_settings()
|
||||
{
|
||||
var logger = new ListLogger();
|
||||
|
||||
FlypaperHttpExtensions.WarnAboutRemovedSettings(new ConfigurationBuilder().Build(), logger);
|
||||
|
||||
logger.Entries.ShouldBeEmpty();
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
using Flypaper.Http;
|
||||
using Flypaper.Http.Matching;
|
||||
using Flypaper.Tests.Fakes;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Http;
|
||||
|
||||
public sealed class TrapMatcherTests
|
||||
{
|
||||
private readonly TrapMatcher _matcher = new(TestOptions.Monitor(new HttpTrapOptions
|
||||
{
|
||||
KnownHosts = ["example.com", "*.example.org"],
|
||||
TrapPaths = ["/.env", "/.git/*", "/wp-login.php"]
|
||||
}));
|
||||
|
||||
[Theory]
|
||||
[InlineData("example.com", "/")]
|
||||
[InlineData("EXAMPLE.com", "/index.html")]
|
||||
[InlineData("app.example.org", "/api/items")]
|
||||
[InlineData("example.com", "/.envelope")]
|
||||
[InlineData("example.com", "/.git")]
|
||||
public void Lets_normal_requests_pass(string host, string path) =>
|
||||
_matcher.Match(host, path).ShouldBe(TrapMatch.None);
|
||||
|
||||
[Theory]
|
||||
[InlineData("example.com", "/.env")]
|
||||
[InlineData("example.com", "/.ENV")]
|
||||
[InlineData("example.com", "/.env/")]
|
||||
[InlineData("example.com", "/.git/config")]
|
||||
[InlineData("app.example.org", "/wp-login.php")]
|
||||
public void Traps_configured_paths(string host, string path) =>
|
||||
_matcher.Match(host, path).ShouldBe(TrapMatch.TrapPath);
|
||||
|
||||
[Theory]
|
||||
[InlineData("unknown.net", "/")]
|
||||
[InlineData("203.0.113.7", "/")]
|
||||
[InlineData("example.org", "/")]
|
||||
[InlineData("", "/")]
|
||||
[InlineData(null, "/")]
|
||||
public void Traps_unknown_hosts(string? host, string path) =>
|
||||
_matcher.Match(host, path).ShouldBe(TrapMatch.UnknownHost);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Storage.Queries;
|
||||
using Flypaper.Tests.Fakes;
|
||||
using Flypaper.Web.Mcp;
|
||||
using ModelContextProtocol;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Mcp;
|
||||
|
||||
public sealed class FlypaperToolsTests : IDisposable
|
||||
{
|
||||
private readonly McpTestData _data = new();
|
||||
private readonly FlypaperTools _tools;
|
||||
|
||||
public FlypaperToolsTests()
|
||||
{
|
||||
var governor = Substitute.For<IConnectionGovernor>();
|
||||
governor.ActiveConnections.Returns(2);
|
||||
_tools = new FlypaperTools(new CatchQueries(_data.Factory), governor, new FixedTimeProvider(McpTestData.Now));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Get_stats_summarizes_the_period()
|
||||
{
|
||||
var stats = await _tools.GetStats("24h");
|
||||
|
||||
stats.Period.ShouldBe("24h");
|
||||
stats.Since.ShouldBe(McpTestData.Now.UtcDateTime.AddHours(-24));
|
||||
stats.Catches.ShouldBe(3);
|
||||
stats.Rejected.ShouldBe(1);
|
||||
stats.UniqueIps.ShouldBe(2);
|
||||
stats.TotalHoldSeconds.ShouldBe(3750);
|
||||
stats.AverageHoldSeconds.ShouldBe(1250);
|
||||
stats.ActiveTraps.ShouldBe(2);
|
||||
stats.LongestCatch.ShouldNotBeNull().DurationSeconds.ShouldBe(3600);
|
||||
stats.LongestCatch!.Country.ShouldBe("China");
|
||||
stats.LongestCatch.Asn.ShouldBe("AS4134");
|
||||
stats.LongestCatch.StartedAt.Kind.ShouldBe(DateTimeKind.Utc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Get_stats_for_all_time()
|
||||
{
|
||||
var stats = await _tools.GetStats("all");
|
||||
|
||||
stats.Since.ShouldBeNull();
|
||||
stats.Catches.ShouldBe(5);
|
||||
stats.UniqueIps.ShouldBe(4);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("yesterday")]
|
||||
[InlineData("0h")]
|
||||
[InlineData("-1d")]
|
||||
public async Task Rejects_invalid_periods(string period) =>
|
||||
await Should.ThrowAsync<McpException>(() => _tools.GetStats(period));
|
||||
|
||||
[Fact]
|
||||
public async Task List_catches_returns_newest_first_with_rejected_ones()
|
||||
{
|
||||
var result = await _tools.ListCatches();
|
||||
|
||||
result.Count.ShouldBe(6);
|
||||
result.Catches.Select(c => c.StartedAt).ShouldBeInOrder(SortDirection.Descending);
|
||||
result.Catches.ShouldContain(c => c.Outcome == "Rejected");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("cn", null, null, null, 2)]
|
||||
[InlineData(null, "AS3462", null, null, 2)]
|
||||
[InlineData(null, "google", null, null, 1)]
|
||||
[InlineData(null, null, "198.51.100.7", null, 2)]
|
||||
[InlineData(null, null, null, ".ENV", 2)]
|
||||
[InlineData("CN", null, null, "wp-login", 1)]
|
||||
public async Task List_catches_filters(string? country, string? provider, string? ip, string? target, int expected)
|
||||
{
|
||||
var result = await _tools.ListCatches(country: country, provider: provider, ip: ip, target_contains: target);
|
||||
|
||||
result.Count.ShouldBe(expected);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task List_catches_filters_by_time_and_limit()
|
||||
{
|
||||
var since = McpTestData.Now.AddHours(-3.5).ToString("O");
|
||||
var until = McpTestData.Now.AddHours(-1.5).ToString("O");
|
||||
|
||||
(await _tools.ListCatches(since: since, until: until)).Count.ShouldBe(2);
|
||||
(await _tools.ListCatches(limit: 1)).Count.ShouldBe(1);
|
||||
(await _tools.ListCatches(limit: 100_000)).Count.ShouldBe(6);
|
||||
await Should.ThrowAsync<McpException>(() => _tools.ListCatches(since: "last tuesday"));
|
||||
await Should.ThrowAsync<McpException>(() => _tools.ListCatches(ip: "not-an-ip"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("ips", "203.0.113.9", 2)]
|
||||
[InlineData("countries", "CN", 2)]
|
||||
[InlineData("providers", "AS4134", 2)]
|
||||
[InlineData("targets", "GET /.env", 1)]
|
||||
[InlineData("user_agents", "zgrab/0.x", 2)]
|
||||
public async Task Top_ranks_each_dimension(string dimension, string firstKey, int firstCount)
|
||||
{
|
||||
var result = await _tools.Top(dimension, "all");
|
||||
|
||||
result.Dimension.ShouldBe(dimension);
|
||||
result.Items[0].Key.ShouldBe(firstKey);
|
||||
result.Items[0].Catches.ShouldBe(firstCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Top_uses_common_country_names_and_rejects_unknown_dimensions()
|
||||
{
|
||||
var countries = await _tools.Top("countries", "24h");
|
||||
|
||||
countries.Items.Select(i => i.Label).ShouldBe(["China", "Taiwan"]);
|
||||
await Should.ThrowAsync<McpException>(() => _tools.Top("cities"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Longest_catches_are_ordered_by_duration()
|
||||
{
|
||||
var result = await _tools.LongestCatches("all", 3);
|
||||
|
||||
result.Catches.Select(c => c.DurationSeconds).ShouldBe([3600, 900, 120]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Lookup_ip_returns_everything_known()
|
||||
{
|
||||
var result = await _tools.LookupIp("198.51.100.7");
|
||||
|
||||
result.Known.ShouldBeTrue();
|
||||
result.Country.ShouldBe("Taiwan");
|
||||
result.Asn.ShouldBe("AS3462");
|
||||
result.Catches.ShouldBe(1);
|
||||
result.Rejected.ShouldBe(1);
|
||||
result.TotalHoldSeconds.ShouldBe(30);
|
||||
result.FirstSeen.ShouldBe(McpTestData.Now.UtcDateTime.AddHours(-4));
|
||||
result.LastSeen.ShouldBe(McpTestData.Now.UtcDateTime.AddHours(-3).AddSeconds(30));
|
||||
result.Events.Count.ShouldBe(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Lookup_ip_handles_unknown_and_invalid_addresses()
|
||||
{
|
||||
(await _tools.LookupIp("192.0.2.99")).Known.ShouldBeFalse();
|
||||
(await _tools.LookupIp("2001:0db8::0001")).Known.ShouldBeTrue();
|
||||
await Should.ThrowAsync<McpException>(() => _tools.LookupIp("999.1.1.1"));
|
||||
}
|
||||
|
||||
public void Dispose() => _data.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Flypaper.Web.Mcp;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Mcp;
|
||||
|
||||
public sealed class McpEndpointTests : IDisposable
|
||||
{
|
||||
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-mcp-http-{Guid.NewGuid():N}.db");
|
||||
private readonly WebApplicationFactory<Program> _factory;
|
||||
|
||||
public McpEndpointTests()
|
||||
{
|
||||
_factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseSetting("ConnectionStrings:Flypaper", $"Data Source={_dbPath}");
|
||||
builder.UseSetting("Flypaper:Ports:Dashboard", "0");
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Rejects_requests_without_token()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
|
||||
var response = await client.SendAsync(Rpc("tools/list", token: null));
|
||||
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
response.Headers.WwwAuthenticate.ToString().ShouldStartWith("Bearer");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Rejects_requests_with_wrong_token()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
await _factory.Services.GetRequiredService<McpTokenService>().CreateAsync("real");
|
||||
|
||||
var response = await client.SendAsync(Rpc("tools/list", token: "fpm_wrong"));
|
||||
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Serves_initialize_tools_list_and_get_stats_with_valid_token()
|
||||
{
|
||||
using var client = _factory.CreateClient();
|
||||
var token = await _factory.Services.GetRequiredService<McpTokenService>().CreateAsync("test");
|
||||
|
||||
var initialize = await ReadAsync(await client.SendAsync(Rpc("initialize", token, new
|
||||
{
|
||||
protocolVersion = "2025-06-18",
|
||||
capabilities = new { },
|
||||
clientInfo = new { name = "test", version = "1.0" }
|
||||
})));
|
||||
initialize.GetProperty("result").GetProperty("serverInfo").GetProperty("name").GetString().ShouldBe("flypaper");
|
||||
|
||||
var tools = await ReadAsync(await client.SendAsync(Rpc("tools/list", token)));
|
||||
var listed = tools.GetProperty("result").GetProperty("tools").EnumerateArray().ToList();
|
||||
listed.Select(t => t.GetProperty("name").GetString())
|
||||
.ShouldBe(["get_stats", "list_catches", "longest_catches", "lookup_ip", "top"], ignoreOrder: true);
|
||||
listed.ShouldAllBe(t => t.GetProperty("annotations").GetProperty("readOnlyHint").GetBoolean());
|
||||
listed.Where(t => !t.TryGetProperty("outputSchema", out var schema) || schema.ValueKind != JsonValueKind.Object).ShouldBeEmpty();
|
||||
|
||||
var stats = await ReadAsync(await client.SendAsync(Rpc("tools/call", token, new { name = "get_stats", arguments = new { period = "all" } })));
|
||||
var structured = stats.GetProperty("result").GetProperty("structuredContent");
|
||||
structured.GetProperty("catches").GetInt32().ShouldBe(0);
|
||||
structured.GetProperty("period").GetString().ShouldBe("all");
|
||||
}
|
||||
|
||||
private static HttpRequestMessage Rpc(string method, string? token, object? parameters = null)
|
||||
{
|
||||
var body = JsonSerializer.Serialize(new { jsonrpc = "2.0", id = 1, method, @params = parameters ?? new { } });
|
||||
var request = new HttpRequestMessage(HttpMethod.Post, "/mcp")
|
||||
{
|
||||
Content = new StringContent(body, Encoding.UTF8, "application/json")
|
||||
};
|
||||
request.Headers.Accept.ParseAdd("application/json");
|
||||
request.Headers.Accept.ParseAdd("text/event-stream");
|
||||
request.Headers.Add("MCP-Protocol-Version", "2025-06-18");
|
||||
if (token is not null)
|
||||
{
|
||||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
private static async Task<JsonElement> ReadAsync(HttpResponseMessage response)
|
||||
{
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
var text = await response.Content.ReadAsStringAsync();
|
||||
var json = response.Content.Headers.ContentType?.MediaType == "text/event-stream"
|
||||
? string.Join("", text.Split('\n').Where(l => l.StartsWith("data:", StringComparison.Ordinal)).Select(l => l[5..].Trim()))
|
||||
: text;
|
||||
return JsonDocument.Parse(json).RootElement.Clone();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_factory.Dispose();
|
||||
SqliteConnection.ClearAllPools();
|
||||
foreach (var suffix in new[] { "", "-wal", "-shm" })
|
||||
{
|
||||
File.Delete(_dbPath + suffix);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Storage;
|
||||
using Flypaper.Storage.Entities;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Flypaper.Tests.Mcp;
|
||||
|
||||
internal sealed class McpTestData : IDisposable
|
||||
{
|
||||
public static readonly DateTimeOffset Now = new(2026, 11, 15, 12, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-mcp-{Guid.NewGuid():N}.db");
|
||||
|
||||
public McpTestData()
|
||||
{
|
||||
Factory = new TestDbContextFactory($"Data Source={_dbPath}");
|
||||
using var db = Factory.CreateDbContext();
|
||||
db.Database.Migrate();
|
||||
|
||||
Add(db, "203.0.113.9", hoursAgo: 1, seconds: 3600, "CN", "Volksrepublik China", "Beijing", 4134, "Chinanet", "GET /.env", "zgrab/0.x");
|
||||
Add(db, "203.0.113.9", hoursAgo: 2, seconds: 120, "CN", "Volksrepublik China", "Beijing", 4134, "Chinanet", "GET example.com/wp-login.php", "zgrab/0.x");
|
||||
Add(db, "198.51.100.7", hoursAgo: 3, seconds: 30, "TW", "Republik China", "Taipeh", 3462, "Data Communication Business Group", "GET /.git/config", "curl/8.5.0");
|
||||
Add(db, "2001:db8::1", hoursAgo: 30, seconds: 900, "US", "Vereinigte Staaten von Amerika", "Mountain View", 15169, "Google LLC", "POST /xmlrpc.php", "python-requests/2.31");
|
||||
Add(db, "198.51.100.7", hoursAgo: 4, seconds: 0, "TW", "Republik China", "Taipeh", 3462, "Data Communication Business Group", "GET /.env", "curl/8.5.0", TrapOutcome.Rejected);
|
||||
Add(db, "192.0.2.50", hoursAgo: 200, seconds: 5, null, null, null, null, null, "GET /", null);
|
||||
db.SaveChanges();
|
||||
}
|
||||
|
||||
public IDbContextFactory<FlypaperDbContext> Factory { get; }
|
||||
|
||||
private static void Add(
|
||||
FlypaperDbContext db,
|
||||
string ip,
|
||||
int hoursAgo,
|
||||
int seconds,
|
||||
string? countryCode,
|
||||
string? country,
|
||||
string? city,
|
||||
long? asn,
|
||||
string? provider,
|
||||
string target,
|
||||
string? userAgent,
|
||||
TrapOutcome outcome = TrapOutcome.ClientAborted)
|
||||
{
|
||||
var started = Now.AddHours(-hoursAgo);
|
||||
var entity = TrapEventEntity.From(new TrapEvent(
|
||||
Guid.NewGuid(),
|
||||
TrapProtocol.Http,
|
||||
IPAddress.Parse(ip),
|
||||
"html-drip",
|
||||
started,
|
||||
started.AddSeconds(seconds),
|
||||
seconds * 10,
|
||||
outcome,
|
||||
target,
|
||||
userAgent));
|
||||
entity.ApplyOrigin(countryCode is null && asn is null ? null : new IpOrigin(countryCode, country, city, asn, provider));
|
||||
db.TrapEvents.Add(entity);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
SqliteConnection.ClearAllPools();
|
||||
foreach (var suffix in new[] { "", "-wal", "-shm" })
|
||||
{
|
||||
File.Delete(_dbPath + suffix);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TestDbContextFactory(string connectionString) : IDbContextFactory<FlypaperDbContext>
|
||||
{
|
||||
public FlypaperDbContext CreateDbContext() =>
|
||||
new(new DbContextOptionsBuilder<FlypaperDbContext>().UseSqlite(connectionString).Options);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using Flypaper.Storage.Settings;
|
||||
using Flypaper.Tests.Fakes;
|
||||
using Flypaper.Web.Mcp;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Mcp;
|
||||
|
||||
public sealed class McpTokenServiceTests : IDisposable
|
||||
{
|
||||
private readonly McpTestData _data = new();
|
||||
private readonly McpTokenStore _store;
|
||||
|
||||
public McpTokenServiceTests() => _store = new McpTokenStore(_data.Factory, new FixedTimeProvider(McpTestData.Now));
|
||||
|
||||
[Fact]
|
||||
public async Task Created_token_is_valid_and_stored_only_as_hash()
|
||||
{
|
||||
var service = Create(environmentToken: null);
|
||||
|
||||
var token = await service.CreateAsync("Claude Desktop");
|
||||
|
||||
token.Length.ShouldBeGreaterThan(40);
|
||||
(await service.ValidateAsync(token)).ShouldBeTrue();
|
||||
var stored = (await _store.ListAsync()).ShouldHaveSingleItem();
|
||||
stored.Name.ShouldBe("Claude Desktop");
|
||||
stored.TokenHash.ShouldBe(McpTokenService.Hash(token));
|
||||
stored.TokenHash.ShouldNotContain(token);
|
||||
stored.LastUsedAt.ShouldBe(McpTestData.Now.UtcDateTime);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Wrong_missing_and_revoked_tokens_are_rejected()
|
||||
{
|
||||
var service = Create(environmentToken: null);
|
||||
var token = await service.CreateAsync("test");
|
||||
|
||||
(await service.ValidateAsync(null)).ShouldBeFalse();
|
||||
(await service.ValidateAsync("")).ShouldBeFalse();
|
||||
(await service.ValidateAsync(token + "x")).ShouldBeFalse();
|
||||
|
||||
(await _store.RevokeAsync((await _store.ListAsync())[0].Id)).ShouldBeTrue();
|
||||
(await service.ValidateAsync(token)).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Environment_token_is_accepted_alongside_stored_ones()
|
||||
{
|
||||
var service = Create(environmentToken: "fixed-token-from-environment");
|
||||
var stored = await service.CreateAsync("test");
|
||||
|
||||
service.UsesEnvironmentToken.ShouldBeTrue();
|
||||
(await service.ValidateAsync("fixed-token-from-environment")).ShouldBeTrue();
|
||||
(await service.ValidateAsync(stored)).ShouldBeTrue();
|
||||
(await service.ValidateAsync("fixed-token")).ShouldBeFalse();
|
||||
}
|
||||
|
||||
private McpTokenService Create(string? environmentToken) =>
|
||||
new(_store, Options.Create(new McpOptions { Token = environmentToken }));
|
||||
|
||||
public void Dispose() => _data.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
using Flypaper.Storage.Queries;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Mcp;
|
||||
|
||||
public sealed class QueryPeriodTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("30m", 0.5)]
|
||||
[InlineData("1h", 1)]
|
||||
[InlineData("24H", 24)]
|
||||
[InlineData("7d", 168)]
|
||||
[InlineData("2w", 336)]
|
||||
public void Parses_relative_periods(string value, double hours)
|
||||
{
|
||||
QueryPeriod.TryParse(value, out var span).ShouldBeTrue();
|
||||
span.ShouldBe(TimeSpan.FromHours(hours));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("all")]
|
||||
[InlineData("")]
|
||||
[InlineData(null)]
|
||||
public void Treats_all_as_unbounded(string? value)
|
||||
{
|
||||
QueryPeriod.TryParse(value, out var span).ShouldBeTrue();
|
||||
span.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("0d")]
|
||||
[InlineData("1y")]
|
||||
[InlineData("1.5h")]
|
||||
[InlineData("h")]
|
||||
public void Rejects_other_values(string value) => QueryPeriod.TryParse(value, out _).ShouldBeFalse();
|
||||
}
|
||||
@@ -43,6 +43,22 @@ public sealed class MigrationTests : IDisposable
|
||||
.ShouldBe(["GET /boaform/admin/formLogin", "GET example.com/.env"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Removes_obsolete_trap_path_and_known_host_overrides()
|
||||
{
|
||||
await using var db = new FlypaperDbContext(new DbContextOptionsBuilder<FlypaperDbContext>().UseSqlite($"Data Source={_dbPath}").Options);
|
||||
await db.GetService<IMigrator>().MigrateAsync("AddMcpTokens");
|
||||
await db.Database.ExecuteSqlRawAsync(
|
||||
"""
|
||||
INSERT INTO "Settings" ("Key", "Value")
|
||||
VALUES ('Flypaper:Http:ExtraKnownHosts', 'example.com'), ('Flypaper:Http:TrapPathsOverride', '/.env'), ('Flypaper:MaxConnections', '50')
|
||||
""");
|
||||
|
||||
await db.Database.MigrateAsync();
|
||||
|
||||
(await db.Settings.Select(s => s.Key).ToListAsync()).ShouldBe(["Flypaper:MaxConnections"]);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
SqliteConnection.ClearAllPools();
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
using Flypaper.Core;
|
||||
using Flypaper.Core.Settings;
|
||||
using Flypaper.Core.Strategies;
|
||||
using Flypaper.Http;
|
||||
using Flypaper.Http.Matching;
|
||||
using Flypaper.Storage;
|
||||
using Flypaper.Storage.Entities;
|
||||
using Flypaper.Storage.Maintenance;
|
||||
using Flypaper.Storage.Settings;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
@@ -28,8 +29,8 @@ public sealed class SettingsOverrideTests : IDisposable
|
||||
await db.Database.MigrateAsync();
|
||||
db.Settings.AddRange(
|
||||
new SettingEntity { Key = SettingKeys.MaxConnections, Value = "5" },
|
||||
new SettingEntity { Key = SettingKeys.TrapPaths, Value = "/custom\n/other/*" },
|
||||
new SettingEntity { Key = SettingKeys.ExtraKnownHosts, Value = "extra.example" },
|
||||
new SettingEntity { Key = SettingKeys.RetentionDays, Value = "30" },
|
||||
new SettingEntity { Key = "Flypaper:Http:TrustedProxies:0", Value = "203.0.113.0/24" },
|
||||
new SettingEntity { Key = "Flypaper:Admin:Password", Value = "evil" });
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
@@ -38,14 +39,12 @@ public sealed class SettingsOverrideTests : IDisposable
|
||||
await host.Services.MigrateFlypaperDatabaseAsync();
|
||||
|
||||
var core = host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>().CurrentValue;
|
||||
var http = host.Services.GetRequiredService<IOptionsMonitor<HttpTrapOptions>>().CurrentValue;
|
||||
var configuration = host.Services.GetRequiredService<IConfiguration>();
|
||||
|
||||
core.MaxConnections.ShouldBe(5);
|
||||
core.MaxConnectionsPerIp.ShouldBe(10);
|
||||
http.TrapPaths.ShouldBe(["/custom", "/other/*"]);
|
||||
http.KnownHosts.ShouldBe(["dashboard.lan", "extra.example"]);
|
||||
http.TrustedProxies.ShouldBe(["172.18.0.0/16"]);
|
||||
host.Services.GetRequiredService<IOptionsMonitor<RetentionOptions>>().CurrentValue.Days.ShouldBe(30);
|
||||
host.Services.GetRequiredService<IOptionsMonitor<HttpTrapOptions>>().CurrentValue.TrustedProxies.ShouldBe(["172.18.0.0/16"]);
|
||||
configuration["Flypaper:Admin:Password"].ShouldBe("secret");
|
||||
}
|
||||
|
||||
@@ -56,59 +55,58 @@ public sealed class SettingsOverrideTests : IDisposable
|
||||
await host.Services.MigrateFlypaperDatabaseAsync();
|
||||
|
||||
host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>().CurrentValue.MaxConnections.ShouldBe(100);
|
||||
host.Services.GetRequiredService<IOptionsMonitor<HttpTrapOptions>>().CurrentValue.TrapPaths.ShouldBe(["/.env"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Saving_reloads_trap_matcher_and_reset_restores_startup_values()
|
||||
public async Task Saving_reloads_options_and_reset_restores_startup_values()
|
||||
{
|
||||
var host = BuildHost();
|
||||
await host.Services.MigrateFlypaperDatabaseAsync();
|
||||
var matcher = host.Services.GetRequiredService<TrapMatcher>();
|
||||
var options = host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>();
|
||||
var store = host.Services.GetRequiredService<RuntimeSettingsStore>();
|
||||
|
||||
matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.None);
|
||||
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.TrapPath);
|
||||
matcher.Match("extra.example", "/").ShouldBe(TrapMatch.UnknownHost);
|
||||
await store.SaveAsync(new RuntimeSettings(50, 4, 90, false));
|
||||
|
||||
await store.SaveAsync(new RuntimeSettings(
|
||||
["/custom"],
|
||||
50,
|
||||
4,
|
||||
TimeSpan.FromMinutes(10),
|
||||
["extra.example"],
|
||||
90,
|
||||
true));
|
||||
|
||||
matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.TrapPath);
|
||||
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.None);
|
||||
matcher.Match("extra.example", "/").ShouldBe(TrapMatch.None);
|
||||
options.CurrentValue.MaxConnections.ShouldBe(50);
|
||||
options.CurrentValue.MaxConnectionsPerIp.ShouldBe(4);
|
||||
options.CurrentValue.IgnorePrivateNetworks.ShouldBeFalse();
|
||||
(await store.HasOverridesAsync()).ShouldBeTrue();
|
||||
|
||||
await store.ResetAsync();
|
||||
|
||||
matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.None);
|
||||
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.TrapPath);
|
||||
options.CurrentValue.MaxConnections.ShouldBe(100);
|
||||
options.CurrentValue.IgnorePrivateNetworks.ShouldBeTrue();
|
||||
(await store.HasOverridesAsync()).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Saved_empty_trap_path_list_disables_path_traps()
|
||||
public async Task Hold_method_is_saved_and_reset_separately_from_general_settings()
|
||||
{
|
||||
var host = BuildHost();
|
||||
await host.Services.MigrateFlypaperDatabaseAsync();
|
||||
var matcher = host.Services.GetRequiredService<TrapMatcher>();
|
||||
var core = host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>();
|
||||
var drip = host.Services.GetRequiredService<IOptionsMonitor<DripOptions>>();
|
||||
var store = host.Services.GetRequiredService<RuntimeSettingsStore>();
|
||||
string[] holdKeys = [.. SettingKeys.HoldMethod];
|
||||
|
||||
await host.Services.GetRequiredService<RuntimeSettingsStore>().SaveAsync(new RuntimeSettings(
|
||||
[],
|
||||
50,
|
||||
4,
|
||||
TimeSpan.FromMinutes(10),
|
||||
[],
|
||||
90,
|
||||
true));
|
||||
await store.SaveAsync(new HoldMethodSettings(DripContent.Text, TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 8, 16, TimeSpan.FromMinutes(5)));
|
||||
await store.SaveAsync(new RuntimeSettings(50, 4, 90, true));
|
||||
|
||||
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.None);
|
||||
drip.CurrentValue.Content.ShouldBe(DripContent.Text);
|
||||
drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(200));
|
||||
drip.CurrentValue.MaxChunkSize.ShouldBe(16);
|
||||
core.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(5));
|
||||
core.CurrentValue.MaxConnections.ShouldBe(50);
|
||||
(await store.HasOverridesAsync(holdKeys)).ShouldBeTrue();
|
||||
|
||||
await store.ResetAsync(holdKeys);
|
||||
|
||||
drip.CurrentValue.Content.ShouldBe(DripContent.Html);
|
||||
drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(50));
|
||||
core.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromHours(1));
|
||||
core.CurrentValue.MaxConnections.ShouldBe(50);
|
||||
(await store.HasOverridesAsync(holdKeys)).ShouldBeFalse();
|
||||
(await store.HasOverridesAsync()).ShouldBeTrue();
|
||||
}
|
||||
|
||||
private IHost BuildHost()
|
||||
@@ -119,8 +117,6 @@ public sealed class SettingsOverrideTests : IDisposable
|
||||
["ConnectionStrings:Flypaper"] = $"Data Source={_dbPath}",
|
||||
["Flypaper:MaxConnections"] = "100",
|
||||
["Flypaper:MaxConnectionsPerIp"] = "10",
|
||||
["Flypaper:Http:TrapPaths:0"] = "/.env",
|
||||
["Flypaper:Http:KnownHosts:0"] = "dashboard.lan",
|
||||
["Flypaper:Http:TrustedProxies:0"] = "172.18.0.0/16",
|
||||
["Flypaper:Admin:Password"] = "secret"
|
||||
});
|
||||
|
||||
+1
-2
@@ -10,7 +10,7 @@
|
||||
<Support>https://gitea.anticarnist.de/Tom/Flypaper/issues</Support>
|
||||
<Project>https://gitea.anticarnist.de/Tom/Flypaper</Project>
|
||||
<Overview>Self-hosted tarpit that traps and slows down scanning bots, with event logging and analysis. Instead of blocking bots, Flypaper answers them with an endless HTML page that trickles in a few bytes at a time, and logs every catch with its country and network provider.[br][br]
|
||||
The trap port receives everything your reverse proxy has no site for (its catch-all / default server) and, optionally, bait paths such as /.env from your real domains. The dashboard has its own port: keep it inside your LAN. On first visit you set the admin password.[br][br]
|
||||
The trap port receives everything your reverse proxy has no site for (its catch-all / default server); every request there is caught. The dashboard has its own port: keep it inside your LAN. On first visit you set the admin password.[br][br]
|
||||
The container starts as root only to hand the appdata folder to its app user (UID 1654), then drops privileges for good.</Overview>
|
||||
<Category>Security: Network:Proxy</Category>
|
||||
<WebUI>http://[IP]:[PORT:8081]/</WebUI>
|
||||
@@ -28,5 +28,4 @@ The container starts as root only to hand the appdata folder to its app user (UI
|
||||
<Config Name="Data" Target="/data" Default="/mnt/user/appdata/flypaper" Mode="rw" Description="Database, login keys and GeoIP databases." Type="Path" Display="always" Required="true" Mask="false">/mnt/user/appdata/flypaper</Config>
|
||||
<Config Name="Admin password" Target="Flypaper__Admin__Password" Default="" Mode="" Description="Optional. Fixes the dashboard password and disables the first-visit setup. Leave empty to set it in the dashboard." Type="Variable" Display="advanced" Required="false" Mask="true"/>
|
||||
<Config Name="Trusted proxy" Target="Flypaper__Http__TrustedProxies__0" Default="" Mode="" Description="Optional. IP or CIDR of the reverse proxy allowed to set X-Real-IP / X-Forwarded-For. Default: all private networks." Type="Variable" Display="advanced" Required="false" Mask="false"/>
|
||||
<Config Name="Known host" Target="Flypaper__Http__KnownHosts__0" Default="" Mode="" Description="Optional. A host that is caught only on trap paths; its other paths get a plain 404." Type="Variable" Display="advanced" Required="false" Mask="false"/>
|
||||
</Container>
|
||||
Reference in new issue
Block a user