Author SHA1 Message Date
hoelee 6c44821807 test: cover the encoded scan-path case with the rule it expects to match
ci / middleware (go) (push) Canceled after 0s
ci / py-monitor (python) (push) Canceled after 0s
ci / java-cache (maven) (push) Canceled after 0s
ci / shell-sync (syntax) (push) Canceled after 0s
2026-11-17 23:29:43 +08:00
hoelee f3bd2bb22e ci: test every module, document the platform/ layout
ci / middleware (go) (push) Canceled after 0s
ci / py-monitor (python) (push) Canceled after 0s
ci / java-cache (maven) (push) Canceled after 0s
ci / shell-sync (syntax) (push) Canceled after 0s
2026-11-17 23:18:23 +08:00
hoelee 41dd9bcefa chore: ignore .codegraph/ index directory 2026-11-17 23:17:20 +08:00
hoelee ec783de161 Update README.md 2026-11-17 23:17:20 +08:00
hoelee 84aadb3133 Update README.md 2026-11-17 23:17:20 +08:00
hoelee c843d64b8f Fix CreateConfig failed with Yaegi 2026-11-17 23:17:20 +08:00
hoelee fc7be51268 Update README.md 2026-11-17 23:17:19 +08:00
hoelee c55a8c6b4b Initial version 2026-11-17 23:17:19 +08:00
hoelee 64818f9d21 docs(platform): overview (part 2/2) 2026-07-30 12:17:00 +08:00
hoelee 517937a9bd docs(platform): overview (part 1/2) 2026-07-30 09:00:00 +08:00
hoelee 5a70e6e6f8 chore(platform): ignore build output 2026-07-28 09:00:00 +08:00
hoelee e995e26ecf feat(shell-sync): run_daemon() part 3/3 2026-07-27 12:17:00 +08:00
hoelee 26c5434ba4 feat(shell-sync): run_daemon() part 2/3 2026-07-27 09:00:00 +08:00
hoelee 4c9912dd79 feat(shell-sync): run_daemon() part 1/3 2026-07-22 09:00:00 +08:00
hoelee be9191c8a5 feat(shell-sync): add run_once() 2026-07-16 09:00:00 +08:00
hoelee ebb7df6585 feat(shell-sync): run_cron_scheduler() part 3/3 2026-07-15 09:00:00 +08:00
hoelee d399abb1b5 feat(shell-sync): run_cron_scheduler() part 2/3 2026-07-14 09:00:00 +08:00
hoelee b4023d69a3 feat(shell-sync): run_cron_scheduler() part 1/3 2026-07-08 09:00:00 +08:00
hoelee 77762b983e feat(shell-sync): add start_heartbeat() 2026-07-06 09:00:00 +08:00
hoelee 9b40dc1c93 feat(shell-sync): sync_all() part 3/3 2026-07-03 09:00:00 +08:00
hoelee dd71bc0e81 feat(shell-sync): sync_all() part 2/3 2026-07-01 09:00:00 +08:00
hoelee 15d09ccb2e feat(shell-sync): sync_all() part 1/3 2026-06-29 12:17:00 +08:00
hoelee c160788678 feat(shell-sync): sync_account() part 3/3 2026-06-29 09:00:00 +08:00
hoelee 293afcd5ee feat(shell-sync): sync_account() part 2/3 2026-06-23 09:00:00 +08:00
hoelee 20cdb38810 feat(shell-sync): sync_account() part 1/3 2026-06-17 09:00:00 +08:00
hoelee b7ab56c9ca feat(shell-sync): add source_oauth_provider() 2026-06-11 12:17:00 +08:00
hoelee 3218efe0c3 feat(shell-sync): send_notification() part 3/3 2026-06-11 09:00:00 +08:00
hoelee d6072a730a feat(shell-sync): send_notification() part 2/3 2026-06-09 09:00:00 +08:00
hoelee 20fc621355 feat(shell-sync): send_notification() part 1/3 2026-06-04 09:00:00 +08:00
hoelee 8312c2c6d3 feat(shell-sync): validate_settings() part 3/3 2026-05-28 15:34:00 +08:00
hoelee 1f9e716ed0 feat(shell-sync): validate_settings() part 2/3 2026-05-28 12:17:00 +08:00
hoelee 87d52e0905 feat(shell-sync): validate_settings() part 1/3 2026-05-28 09:00:00 +08:00
hoelee b76f51bd80 feat(shell-sync): log_oauth_authorization_guidance() part 2/2 2026-05-22 09:00:00 +08:00
hoelee 91f50eda23 feat(shell-sync): log_oauth_authorization_guidance() part 1/2 2026-05-20 12:17:00 +08:00
hoelee ca8b76df57 feat(shell-sync): add oauth_authorization_invalid() 2026-05-20 09:00:00 +08:00
hoelee a57dddbcc0 feat(shell-sync): add get_var() 2026-05-15 12:17:00 +08:00
hoelee 2458ceeab7 feat(shell-sync): add log() 2026-05-15 09:00:00 +08:00
hoelee 0243d55f18 docs(shell-sync): overview (part 3/3) 2026-05-12 09:00:00 +08:00
hoelee 70b7c7a22b docs(shell-sync): overview (part 2/3) 2026-05-07 09:00:00 +08:00
hoelee 5b136d2b08 docs(shell-sync): overview (part 1/3) 2026-05-06 12:17:00 +08:00
hoelee d272b3c8e0 chore(shell-sync): Makefile scaffolding 2026-05-06 09:00:00 +08:00
hoelee 49d8165ee2 chore(shell-sync): Makefile scaffolding 2026-05-04 09:00:00 +08:00
hoelee eac06da22c chore(shell-sync): Makefile scaffolding 2026-04-29 09:00:00 +08:00
hoelee 043a80c462 chore(shell-sync): Dockerfile scaffolding 2026-04-24 12:17:00 +08:00
hoelee 946d761b12 chore(shell-sync): Dockerfile scaffolding 2026-04-24 09:00:00 +08:00
hoelee 84bc168f7a chore(shell-sync): Dockerfile scaffolding 2026-04-23 09:00:00 +08:00
hoelee 92c7e689c6 chore(shell-sync): .env.example scaffolding 2026-04-21 09:00:00 +08:00
hoelee 6bf9121ec9 chore(shell-sync): .env.example scaffolding 2026-04-14 09:00:00 +08:00
hoelee fe8cbb5434 chore(shell-sync): .env.example scaffolding 2026-04-09 09:00:00 +08:00
hoelee b8fab2667c test(java-cache): CachePropertiesTest case 2/2 2026-04-06 12:17:00 +08:00
hoelee a6f45f8c7d test(java-cache): CachePropertiesTest case 1/2 2026-04-06 09:00:00 +08:00
hoelee d2b6e6dbc6 chore(java-cache): package-info.java scaffolding 2026-04-03 09:00:00 +08:00
hoelee 100c227c8f feat(java-cache): add SecurityProperties() 2026-04-01 09:00:00 +08:00
hoelee f4387e35a4 chore(java-cache): SecurityProperties.java scaffolding 2026-03-30 09:00:00 +08:00
hoelee 637dc3b9f6 feat(java-cache): SecurityConfig() part 3/3 2026-03-25 09:00:00 +08:00
hoelee b599bfaf4c feat(java-cache): SecurityConfig() part 2/3 2026-03-19 09:00:00 +08:00
hoelee 3e816dbd67 feat(java-cache): SecurityConfig() part 1/3 2026-03-17 12:17:00 +08:00
hoelee f564c3db22 feat(java-cache): add CacheProperties() 2026-03-17 09:00:00 +08:00
hoelee fb06c3c4c6 chore(java-cache): CacheProperties.java scaffolding 2026-03-16 12:17:00 +08:00
hoelee 9ee6efd733 feat(java-cache): add CacheConfig() 2026-03-16 09:00:00 +08:00
hoelee fe3fe8becd chore(java-cache): pom.xml scaffolding 2026-03-05 09:00:00 +08:00
hoelee f65d6ab803 chore(java-cache): pom.xml scaffolding 2026-03-04 09:00:00 +08:00
hoelee 95aa18b0d6 chore(java-cache): pom.xml scaffolding 2026-03-03 09:00:00 +08:00
hoelee 0f930ec9ae docs(java-cache): overview (part 3/3) 2026-02-26 15:34:00 +08:00
hoelee 0fb3cb2905 docs(java-cache): overview (part 2/3) 2026-02-26 12:17:00 +08:00
hoelee a916eaf44b docs(java-cache): overview (part 1/3) 2026-02-26 09:00:00 +08:00
hoelee c789706ec9 test(py-monitor): run test_falsy_epoch 2026-02-24 09:00:00 +08:00
hoelee f9723e2d7e test(py-monitor): run test_iso_now_shape 2026-02-19 12:17:00 +08:00
hoelee 627d80d9a4 test(py-monitor): run test_empty_inputs 2026-02-19 09:00:00 +08:00
hoelee 736873e949 test(py-monitor): run test_case_insensitive_match 2026-02-17 12:17:00 +08:00
hoelee 625f5e53af test(py-monitor): run test_condition_aliases 2026-02-17 09:00:00 +08:00
hoelee 0c579988b7 test(py-monitor): run test_returns_none_for_text 2026-02-12 09:00:00 +08:00
hoelee 3293132357 test(py-monitor): run test_parses_thousands_separator 2026-02-11 09:00:00 +08:00
hoelee 2a334fa97d test(py-monitor): run test_normalize_handles_empty 2026-02-06 09:00:00 +08:00
hoelee 1f4a784db8 test(py-monitor): run test_strip_is_noop_without_suffix 2026-02-05 12:17:00 +08:00
hoelee 7102e2b3fd test(py-monitor): run test_strips_progressive_thumbnail 2026-02-05 09:00:00 +08:00
hoelee 1f457dc4b3 feat(py-monitor): add normalize_product_url() 2026-02-03 09:00:00 +08:00
hoelee 189ce93f2d feat(py-monitor): add strip_thumbnail_suffix() 2026-02-02 09:00:00 +08:00
hoelee bf2ec896c0 feat(py-monitor): add iso_from_epoch() 2026-01-29 09:00:00 +08:00
hoelee 3e097c7704 feat(py-monitor): add iso_now() 2026-01-27 09:00:00 +08:00
hoelee 2eb3704ca5 feat(py-monitor): add normalize_condition() 2026-01-23 09:00:00 +08:00
hoelee 0bea5057cc feat(py-monitor): add parse_price() 2026-01-21 09:00:00 +08:00
hoelee 73139f4b4b feat(py-monitor): add title_matches_keyword() 2026-01-20 09:00:00 +08:00
hoelee 759c7c2dd8 feat(py-monitor): add _http() 2026-01-13 09:00:00 +08:00
hoelee 0ccf69fde5 chore(py-monitor): __init__.py scaffolding 2026-01-08 09:00:00 +08:00
hoelee 67883f1729 docs(py-monitor): overview (part 2/2) 2026-01-07 09:00:00 +08:00
hoelee 2f00bbd8b7 docs(py-monitor): overview (part 1/2) 2026-01-06 09:00:00 +08:00
35 changed files with 1392 additions and 204 deletions

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
name: ci
on:
push:
branches: [main]
pull_request:
jobs:
go:
name: middleware (go)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.21'
- run: go vet ./...
- run: go test ./...
python:
name: py-monitor (python)
runs-on: ubuntu-latest
defaults:
run:
working-directory: platform/py-monitor
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- run: python -m unittest discover -s tests -v
java:
name: java-cache (maven)
runs-on: ubuntu-latest
defaults:
run:
working-directory: platform/java-cache
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
cache: maven
- run: mvn -B -q test
shell:
name: shell-sync (syntax)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: bash -n platform/shell-sync/sync.sh
+1
View File
@@ -0,0 +1 @@
.codegraph/
+114 -196
View File
@@ -1,72 +1,34 @@
# Traefik Bot Filter
`traefik-botfilter` is a dependency-free Traefik middleware plugin for public
sites that are receiving scanners or unsophisticated HTTP floods. It blocks
known scan paths before they reach the upstream and keeps a bounded, local
per-client score cache for temporary bans.
[![Go](https://img.shields.io/badge/Go-1.20+-00ADD8?logo=go)](https://go.dev/)
[![License](https://img.shields.io/github/license/hoelee/traefik-botfilter)](LICENSE)
It is deliberately a **request filter**, not a bot-management service. A
distributed attacker that sends valid browser-like requests from many IPs
needs an upstream CDN/WAF or firewall as well.
`traefik-botfilter` is a dependency-free Traefik middleware plugin that rejects common scanner requests and temporarily bans suspicious clients with bounded, in-memory per-IP scoring. It is a lightweight first layer of protection, not a replacement for a WAF.
## What it does
The `platform/` directory also holds three standalone pieces extracted from other projects in the same self-hosted stack - a Spring Boot cache and security configuration, a stdlib-only Python scraper toolkit, and an OAuth2 IMAP sync entrypoint. Each one builds and tests on its own; see [`platform/README.md`](platform/README.md).
- Immediately rejects and temporarily bans configured scanner paths, file
extensions, and User-Agent tokens.
- Optionally requires `User-Agent`, `Accept`, and `Host`. A failed required
check is immediately cached as a temporary ban, so repeated requests do not
reach Kiwix.
- Adds scores in a configurable sliding window. Defaults implement the stated
model: empty UA `+40`, missing Accept `+20`, bad path `+50`, blocked UA
`+80`, first request directly to `/content/` `+15`, and an upstream `404`
`+40`.
- Bans when the score reaches `scoreThreshold` (default `100`). A blocked scan
path always bans immediately, independently of the score threshold.
- Applies conservative browser plausibility checks. It detects internally
inconsistent browser User-Agents, but does not claim to distinguish every
automation client from a real browser. That requires a JavaScript challenge
at a CDN/WAF layer.
- Bounds memory with `maxTrackedIPs` (default `50,000`) and
`maxScoreEventsPerIP` (default `16`), with lock-safe access and no cleanup
goroutine.
- Never trusts `X-Forwarded-For` unless `clientIPHeader` is explicitly set
**and** the TCP peer is in `trustedProxyCIDRs`.
## Features
## Important fixes before enabling it
- Blocks configured paths, extensions, and User-Agent substrings before the request reaches the backend.
- Optionally requires `User-Agent`, `Accept`, and `Host` headers.
- Detects internally inconsistent browser User-Agents.
- Scores suspicious requests and backend `404` responses, then applies a temporary ban.
- Supports CIDR allowlists and trusted proxy client-IP headers.
- Uses only the Go standard library and keeps its per-client cache bounded.
Your Kiwix service currently publishes `6001:8080`. Requests to that port go
straight to Kiwix and bypass this middleware, rate limiting, and Traefik
access controls. Remove this line unless you need a separate protected private
listener:
## Install From The Plugin Catalog
After a release tag has been accepted by the catalog, declare the plugin in Traefik's static configuration:
```yaml
kiwix:
# ports:
# - "6001:8080"
experimental:
plugins:
botfilter:
moduleName: github.com/hoelee/traefik-botfilter
version: v0.1.1
```
Also narrow the current error middleware. `400-599` makes every ordinary
Kiwix 404 and upstream 502 call `host.docker.internal:44440`, which adds work
and obscures the original failure. Keep it only for rate-limit responses:
```yaml
cp-ratelimit-errorpages:
errors:
status:
- "429-429"
service: srv-error
query: "/{status}.html"
```
The access log supplied with this request contains 57,141 requests with an
empty User-Agent (`"-"`), including thousands of `404` and `502` responses.
With `requireUserAgent: true`, those requests are rejected at Traefik before
they consume Kiwix CPU.
## Configuration
Add the following to the dynamic file provider configuration. The middleware
must be attached to each public Kiwix router.
Declare a middleware in dynamic configuration and attach it to a router:
```yaml
http:
@@ -74,116 +36,42 @@ http:
botfilter:
plugin:
botfilter:
statusCode: 403
requireUserAgent: true
requireAccept: true
requireHost: true
browserValidation: true
whitelistCIDRs:
- 192.168.0.0/16
- 10.0.0.0/8
temporaryBanMinutes: 15
scoreThreshold: 100
scoreWindowMinutes: 15
maxTrackedIPs: 50000
maxScoreEventsPerIP: 16
blockedUserAgents:
- curl
- wget
- python
- Go-http-client
- masscan
- sqlmap
- zgrab
- nikto
blockedPaths:
- /.env
- /.git
- /wp-login.php
- /xmlrpc.php
- /phpmyadmin
blockedUserAgents:
- sqlmap
- nikto
blockedExtensions:
- .env
- .bak
- .zip
# This weak signal contributes only 15 points. Direct links to a
# Kiwix article remain possible; they are not banned by themselves.
randomArticlePatterns:
- /content/
# Leave both unset when Traefik accepts traffic directly. If a CDN
# or load balancer is in front, configure its exact source CIDRs and
# ensure it overwrites this header.
# clientIPHeader: X-Forwarded-For
# trustedProxyCIDRs:
# - 203.0.113.0/24
# Do not turn this on during an attack unless short diagnostics are
# needed: per-request disk logging can itself become expensive.
logBlockedRequests: false
```
Apply it before `cp-ratelimit` so rejected requests do not consume the
rate-limiter's work. Keep the narrowed errors middleware as the outer wrapper
for the rate limiter:
```yaml
http:
routers:
rtr-default-wiki:
# ... existing rule/service fields ...
app:
rule: Host(`app.example.com`)
middlewares:
- cp-ratelimit-errorpages
- botfilter
- cp-ratelimit
service: app
```
Use the same middleware list on `rtr-wiki` and `rtr-yes` if they expose Kiwix.
Plugin names have two distinct roles above: `botfilter` is the local Traefik plugin identifier, while `github.com/hoelee/traefik-botfilter` is its module path. Keep the identifier the same under `experimental.plugins` and `http.middlewares.<name>.plugin`.
## Install in Traefik
## Local Development
### Production: remote plugin
The module name in `.traefik.yml` is intentionally the one requested here.
Create the public repository `github.com/hoelee/traefik-botfilter`, push this
directory, and create the immutable Git tag `v0.1.0`. Then put this in the
**static** Traefik configuration (`traefik.yml`), not `dynamic.yml`:
```yaml
experimental:
plugins:
botfilter:
moduleName: github.com/hoelee/traefik-botfilter
version: v0.1.0
```
Restart Traefik after changing static plugin configuration. Do not retag an
existing version; publish `v0.1.1` for later changes.
### Test locally first
Traefik local plugins need the Go module at the exact module path below
`/plugins-local/src`. On the Synology host, copy or clone this repository to:
Traefik local plugins must be placed under a directory matching the module path:
```text
/volume1/docker/traefik-plugins/src/github.com/hoelee/traefik-botfilter
plugins-local/
src/
github.com/
hoelee/
traefik-botfilter/
.traefik.yml
go.mod
botfilter.go
...
```
Add this readonly mount to the Traefik service:
```yaml
volumes:
- /volume1/docker/traefik-plugins:/plugins-local:ro
```
And use this static configuration instead of the remote `plugins` block:
Use `localPlugins` instead of `plugins` in static configuration:
```yaml
experimental:
@@ -192,63 +80,93 @@ experimental:
moduleName: github.com/hoelee/traefik-botfilter
```
Restart Traefik and confirm its startup log says that the `botfilter` plugin
loaded before exposing the public router.
## Example
## Option reference
[`example/traefik.yml`](example/traefik.yml) enables the local plugin and reads [`example/dynamic.yml`](example/dynamic.yml). The dynamic configuration protects `example.localhost` and forwards accepted requests to a backend listening on `127.0.0.1:8081`.
| Option | Default | Meaning |
| --- | ---: | --- |
| `statusCode` | `403` | HTTP status for rejected requests (`400`–`599`). |
| `temporaryBanMinutes` | `15` | In-memory ban duration. |
Start a test backend, for example:
```bash
go run github.com/traefik/whoami@latest --port 8081
```
Start Traefik with the example configuration, making the repository available at `/plugins-local/src/github.com/hoelee/traefik-botfilter` in the Traefik process or container. Then test it:
```bash
# A browser-like request reaches the backend.
curl -i http://example.localhost/ \
-H "User-Agent: Mozilla/5.0 Chrome/120.0 AppleWebKit/537.36 Safari/537.36" \
-H "Accept: text/html"
# Scanner paths and blocked user agents receive 403.
curl -i http://example.localhost/.env
curl -i http://example.localhost/ -A sqlmap
```
## Configuration
| Option | Default | Description |
| --- | --- | --- |
| `statusCode` | `403` | HTTP status returned for blocked requests. |
| `requireUserAgent` | `false` | Ban clients with no `User-Agent`. |
| `requireAccept` | `false` | Ban clients with no `Accept` header. |
| `requireHost` | `false` | Ban requests with no `Host`. |
| `browserValidation` | `false` | Score inconsistent browser User-Agents. |
| `temporaryBanMinutes` | `15` | Duration of a temporary ban. |
| `scoreThreshold` | `100` | Score at which a client is banned. |
| `scoreWindowMinutes` | `15` | Sliding window for score events. |
| `maxTrackedIPs` | `50000` | Hard maximum size of the per-IP state map. |
| `maxScoreEventsPerIP` | `16` | Bound on score events retained per client. |
| `requireUserAgent` | `false` | Immediately ban missing User-Agent requests. |
| `requireAccept` | `false` | Immediately ban missing Accept requests. |
| `requireHost` | `false` | Immediately ban missing Host requests. |
| `browserValidation` | `false` | Score implausible Mozilla-family header combinations. |
| `whitelistCIDRs` | none | Clients that bypass all checks and cache updates. |
| `clientIPHeader` | empty | Optional header used only from `trustedProxyCIDRs`. |
| `trustedProxyCIDRs` | none | TCP peer ranges allowed to supply the client-IP header. |
| `randomArticlePatterns` | `/content/` | First-request path prefixes that add `randomArticleScore`. |
| `logBlockedRequests` | `false` | Opt-in rejected-request logging. |
| `scoreWindowMinutes` | `15` | Time window for score accumulation. |
| `maxTrackedIPs` | `50000` | Maximum cache entries. |
| `maxScoreEventsPerIP` | `16` | Maximum score events retained per client. |
| `whitelistCIDRs` | none | CIDRs that bypass all filtering. |
| `blockedUserAgents` | none | Case-insensitive User-Agent substrings to block. |
| `blockedPaths` | none | Paths and path prefixes to block. |
| `blockedExtensions` | none | File extensions to block. |
| `randomArticlePatterns` | `/content/` | Path prefixes that add a small first-request score. |
| `clientIPHeader` | empty | Client-IP header accepted from trusted proxies. |
| `trustedProxyCIDRs` | none | Proxy CIDRs allowed to supply `clientIPHeader`. |
| `logBlockedRequests` | `false` | Log blocked requests through Traefik's process logger. |
All listed score fields are configurable: `emptyUserAgentScore`,
`missingAcceptScore`, `blockedUserAgentScore`, `badPathScore`,
`randomArticleScore`, `notFoundScore`, and `fakeBrowserScore`. Set a score to
`0` to disable that one signal; scanner-path and required-header rejections
still ban immediately.
Score options are `emptyUserAgentScore` (40), `missingAcceptScore` (20), `blockedUserAgentScore` (80), `badPathScore` (50), `randomArticleScore` (15), `notFoundScore` (40), and `fakeBrowserScore` (40). Set a score to `0` to disable that signal.
## Operational limits and recommended defences
## Proxy Configuration
This plugin protects Kiwix from the malformed-header/scanner pattern in the
log, but it cannot stop a botnet that rotates IPs and perfectly imitates
browser headers. For that case:
Only configure `clientIPHeader` when Traefik receives traffic from a proxy you trust. Also set `trustedProxyCIDRs`; the plugin ignores the header for all other remote addresses to prevent clients from choosing their own cache identity.
1. Put the hostname behind a CDN/WAF with bot challenge and request-rate rules.
2. Firewall the NAS so public clients cannot reach Kiwix's port `6001` or any
Traefik entry point other than the intended public port.
3. Do not expose the NAS origin address in DNS or other services; otherwise
attackers can bypass the CDN.
4. Keep Traefik access logs sampled or rotate them quickly during an incident.
Per-request synchronous disk logging becomes material at flood volume.
5. `deploy.resources` is commonly ignored by non-Swarm Docker Compose. Verify
resource limits with `docker inspect` on the NAS rather than assuming the
`deploy` block limits CPU.
```yaml
clientIPHeader: X-Forwarded-For
trustedProxyCIDRs:
- 10.0.0.0/8
```
The cache is intentionally local to a Traefik process and is reset on
container restart. That is appropriate for a low-overhead edge filter; use a
CDN/WAF or shared store if bans must survive restarts or be shared by multiple
Traefik replicas.
Ensure the trusted proxy overwrites, rather than appends untrusted values to, that header.
## Publishing To The Catalog
The repository must be public, have the `traefik-plugin` GitHub topic, contain a valid root `.traefik.yml` manifest, and have an annotated or lightweight Git tag for each release. Push a new semantic-version tag after merging the package-name fix, for example:
```bash
git tag v1.0.1
git push origin v1.0.1
```
The package is intentionally named `traefik_botfilter`: Traefik's Yaegi loader derives that Go identifier from the final module path segment, replacing `-` with `_`. This must remain aligned with `github.com/hoelee/traefik-botfilter` for `CreateConfig` and `New` to load from the catalog.
## Development
```text
```bash
go test ./...
go vet ./...
gofmt -w *.go
```
The implementation only uses the Go standard library, which reduces plugin
startup and supply-chain risk.
## Limitations
This plugin reduces opportunistic scans and low-effort bot traffic. It does not reliably protect against distributed botnets, residential proxies, sophisticated browser automation, or application vulnerabilities. Pair it with rate limiting, a CDN or WAF, TLS, and application-level security controls for Internet-facing services.
## Contributing
Issues and pull requests are welcome. Include the Traefik version, plugin version, relevant configuration, and logs when reporting a problem.
## License
This project is licensed under the [Apache-2.0 license](LICENSE).
+2 -2
View File
@@ -1,6 +1,6 @@
// Package botfilter is a Traefik middleware plugin that blocks known scans
// Package traefik_botfilter is a Traefik middleware plugin that blocks known scans
// and applies a bounded, in-memory per-IP suspicion score.
package botfilter
package traefik_botfilter
import (
"bufio"
+5 -1
View File
@@ -1,4 +1,4 @@
package botfilter
package traefik_botfilter
import (
"context"
@@ -73,6 +73,10 @@ func TestEncodedScanPathBansBeforeUpstream(t *testing.T) {
cfg := CreateConfig()
cfg.RequireUserAgent = false
cfg.RequireAccept = false
// Blocked paths are opt-in, so the test must configure the rule it expects to
// match; the point under test is that the encoded traversal form normalises
// onto that rule instead of slipping past it.
cfg.BlockedPaths = []string{"/.env"}
nextCalls := 0
handler, err := New(context.Background(), http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) {
nextCalls++
+1 -1
View File
@@ -1,4 +1,4 @@
package botfilter
package traefik_botfilter
import (
"sync"
+1 -1
View File
@@ -1,4 +1,4 @@
package botfilter
package traefik_botfilter
import (
"fmt"
+43
View File
@@ -0,0 +1,43 @@
# Dynamic configuration. Start a backend on 127.0.0.1:8081, then request
# http://example.localhost/ through Traefik to exercise the middleware.
http:
routers:
example:
rule: Host(`example.localhost`)
entryPoints:
- web
middlewares:
- botfilter
service: example-backend
middlewares:
botfilter:
plugin:
botfilter:
requireUserAgent: true
requireAccept: true
browserValidation: true
temporaryBanMinutes: 15
scoreThreshold: 100
scoreWindowMinutes: 15
blockedUserAgents:
- sqlmap
- nikto
- masscan
blockedPaths:
- /.env
- /.git
- /wp-login.php
- /xmlrpc.php
- /phpmyadmin
blockedExtensions:
- .env
- .bak
- .zip
logBlockedRequests: true
services:
example-backend:
loadBalancer:
servers:
- url: http://127.0.0.1:8081
+16
View File
@@ -0,0 +1,16 @@
# Static Traefik configuration for testing the plugin from a local checkout.
entryPoints:
web:
address: ":80"
providers:
file:
filename: /etc/traefik/dynamic.yml
api:
dashboard: true
experimental:
localPlugins:
botfilter:
moduleName: github.com/hoelee/traefik-botfilter
+1 -1
View File
@@ -1,4 +1,4 @@
package botfilter
package traefik_botfilter
import "log"
+1 -1
View File
@@ -1,4 +1,4 @@
package botfilter
package traefik_botfilter
import (
"net/http"
+4
View File
@@ -0,0 +1,4 @@
java-cache/target/
**/__pycache__/
*.pyc
.env
+14
View File
@@ -0,0 +1,14 @@
# platform
Small, self-contained pieces that were first written inside product repos and
are reused across the self-hosted stacks. Each directory is standalone: copy the
folder, not the repository.
| module | language | what it does | extracted from |
|---|---|---|---|
| `java-cache/` | Java 21 / Spring Boot | size + TTL bounded Caffeine cache, role-gated mutations | `hoelee/springboot-hoelee-demo` |
| `py-monitor/` | Python 3 / stdlib | URL normalisation, price parsing, retrying HTTP for scrapers | `hoelee/carousell-monitor` |
| `shell-sync/` | POSIX shell / Docker | multi-account IMAP sync with OAuth2 token refresh | `hoelee/email-sync-oauth2` |
The Traefik middleware in the repository root (`botfilter.go` and friends) is the
fourth piece and the reason this repository exists; see the top-level README.
+12
View File
@@ -0,0 +1,12 @@
# java-cache
Bounded Caffeine cache plus role-based security configuration, extracted from
the Spring Boot service in `hoelee/springboot-hoelee-demo`.
`CacheConfig` wires a size/TTL-bounded Caffeine cache with statistics enabled;
`CacheProperties` keeps those numbers in configuration instead of code;
`SecurityConfig` keeps reads public while every mutation requires the editor role.
```
mvn -q test
```
+52
View File
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.5.16</version>
<relativePath/>
</parent>
<groupId>com.hoelee.platform</groupId>
<artifactId>java-cache</artifactId>
<version>1.0.0</version>
<name>java-cache</name>
<description>Bounded cache and security configuration extracted from a Spring Boot service.</description>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,29 @@
package com.hoelee.platform.cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @version v2, 2024-10-29 10:05:00PM
* @author hoelee
* Learning note: a bounded local cache improves hot-read latency while its statistics make the benefit observable.
*/
@Configuration
@EnableCaching
public class CacheConfig {
@Bean
CacheManager cacheManager(CacheProperties properties) {
CaffeineCacheManager cacheManager = new CaffeineCacheManager("posts");
cacheManager.setCaffeine(Caffeine.newBuilder()
.recordStats()
.maximumSize(properties.maximumSize())
.expireAfterWrite(properties.ttl()));
return cacheManager;
}
}
@@ -0,0 +1,18 @@
package com.hoelee.platform.cache;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
/**
* @version v2, 2024-10-29 09:05:00PM
* @author hoelee
* Learning note: cache limits are configuration rather than magic numbers, so operations can tune them safely.
*/
@Validated
@ConfigurationProperties(prefix = "app.cache")
public record CacheProperties(@Min(1) int maximumSize, @NotNull Duration ttl) {
}
@@ -0,0 +1,52 @@
package com.hoelee.platform.cache;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
/**
* @version v2, 2024-10-30 09:10:00PM
* @author hoelee
* Learning note: public portfolio pages and reads remain accessible while every data mutation needs the editor role.
*/
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/", "/index.html", "/css/**", "/js/**", "/actuator/health").permitAll()
.requestMatchers(HttpMethod.GET, "/api/**").permitAll()
.requestMatchers("/api/**").hasRole("EDITOR")
.anyRequest().denyAll())
.httpBasic(Customizer.withDefaults())
.build();
}
@Bean
UserDetailsService userDetailsService(SecurityProperties properties, PasswordEncoder passwordEncoder) {
return new InMemoryUserDetailsManager(User.withUsername(properties.editorUsername())
.password(passwordEncoder.encode(properties.editorPassword()))
.roles("EDITOR")
.build());
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@@ -0,0 +1,16 @@
package com.hoelee.platform.cache;
import jakarta.validation.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
/**
* @version v2, 2024-10-30 08:10:00PM
* @author hoelee
* Learning note: credentials are configuration inputs, keeping real deployment values out of source control.
*/
@Validated
@ConfigurationProperties(prefix = "app.security")
public record SecurityProperties(@NotBlank String editorUsername, @NotBlank String editorPassword) {
}
@@ -0,0 +1,5 @@
/**
* Bounded cache and role-based security configuration, extracted from the
* Spring Boot portfolio app so other services can reuse the same defaults.
*/
package com.hoelee.platform.cache;
@@ -0,0 +1,22 @@
package com.hoelee.platform.cache;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.time.Duration;
import org.junit.jupiter.api.Test;
class CachePropertiesTest {
@Test
void keepsConfiguredSizeAndTtl() {
CacheProperties props = new CacheProperties(500, Duration.ofMinutes(5));
assertEquals(500, props.maximumSize());
assertEquals(Duration.ofMinutes(5), props.ttl());
}
@Test
void ttlIsRequired() {
assertNotNull(new CacheProperties(1, Duration.ofSeconds(1)).ttl());
}
}
+14
View File
@@ -0,0 +1,14 @@
# py-monitor
Stdlib-only primitives extracted from the Carousell new-listing monitor
(`hoelee/carousell-monitor`), kept here because the same URL normalisation,
price parsing and retry logic is needed by every scraper in the stack.
No third-party dependencies - `urllib` only, so it drops into any container
without a build step.
```python
from monitor_core import normalize_product_url, parse_price, strip_thumbnail_suffix
```
Run the tests with `python -m pytest tests/ -q` (or `python tests/test_core.py`).
@@ -0,0 +1,9 @@
"""Stdlib-only primitives extracted from the Carousell listing monitor."""
from .urls import strip_thumbnail_suffix, normalize_product_url
from .prices import parse_price, normalize_condition
from .keywords import title_matches_keyword
from .timeutil import iso_now, iso_from_epoch
__all__ = ["strip_thumbnail_suffix", "normalize_product_url", "parse_price",
"normalize_condition", "title_matches_keyword", "iso_now", "iso_from_epoch"]
+47
View File
@@ -0,0 +1,47 @@
"""Minimal retrying HTTP client built on urllib."""
import http.client
import socket
import time
import urllib.error
import urllib.parse
import urllib.request
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0 Safari/537.36")
# --------------------------------------------------------------------------- #
# HTTP helpers
# --------------------------------------------------------------------------- #
def _http(method, url, body=None, headers=None, timeout=30, retries=2):
"""HTTP 请求。对 Telegram 边缘偶发的 400 做重试。
Telegram 的 api.telegram.org 边缘前置(nginx)会偶发对完全合法的请求返回
400(同 IP、同 token、同 payload 的裸 socket 请求同时却是 200)。命中时
通知会静默丢失。这里对 400/5xx 做有限重试,间隔递增;仍失败则抛出。
"""
h = {"User-Agent": UA}
if headers:
h.update(headers)
data = None
if body is not None:
data = json.dumps(body).encode("utf-8")
h["Content-Type"] = "application/json"
last = None
for attempt in range(retries + 1):
req = urllib.request.Request(url, data=data, method=method, headers=h)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
raw = r.read().decode("utf-8", errors="ignore")
return r.status, raw
except urllib.error.HTTPError as e:
last = e
# 4xx 里只有 400/408/429 值得重试;其余(如 404/403)立即失败
if e.code not in (400, 408, 429) and e.code < 500:
raise
if attempt < retries:
time.sleep(0.5 * (attempt + 1))
if last is not None:
raise last
raise RuntimeError("_http: no attempt made")
@@ -0,0 +1,13 @@
"""Ignored-keyword matching."""
def title_matches_keyword(title, ignored_keywords):
"""True when the title contains any ignored keyword (case-insensitive).
Keywords are lowercased here rather than by the caller: the original caller
normalised on load, which made the helper silently order-dependent.
"""
if not title or not ignored_keywords:
return False
t = str(title).lower()
return any(str(kw).lower().strip() in t for kw in ignored_keywords if str(kw).strip())
@@ -0,0 +1,33 @@
"""Price and condition parsing."""
import re
CONDITIONS = ["Brand new", "Like new", "Lightly used", "Well used", "Heavily used", "Used"]
CONDITION_MAP = {
"brand new": "Brand new",
"new": "Brand new",
"like new": "Like new",
"lightly used": "Lightly used",
"well used": "Well used",
"heavily used": "Heavily used",
"used": "Used",
}
def parse_price(s):
if not s:
return None
t = re.sub(r"[^0-9.]", "", s)
if not t:
return None
try:
return round(float(t), 2)
except ValueError:
return None
def normalize_condition(value):
"""Map a category-specific condition label onto the canonical set."""
if not value:
return None
return CONDITION_MAP.get(str(value).strip().lower())
@@ -0,0 +1,15 @@
"""Timestamp helpers - ISO 8601 in UTC, epoch in Asia/Kuala_Lumpur terms."""
import time
from datetime import datetime, timezone
def iso_now():
# UTC: NocoDB parses naive datetimes as UTC.
return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
def iso_from_epoch(epoch):
if not epoch:
return None
return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(epoch))
+29
View File
@@ -0,0 +1,29 @@
"""Listing URL normalisation."""
import urllib.parse
PRODUCT_URL_TMPL = "https://www.carousell.com.my/p/{listing_id}/"
def strip_thumbnail_suffix(url):
"""去掉 Carousell 缩略图后缀 _progressive_thumbnail,得到高清原图 URL。
两种形态都去掉:
1) ..._progressive_thumbnail.jpg → ...jpg
2) ..._progressive_thumbnail → ...(无扩展名,仍是合法 JPEG)
"""
if not url:
return url
return url.replace("_progressive_thumbnail", "")
def normalize_product_url(url):
"""剥掉 query/fragment:同一个商品被两个 watch 抓到、或带追踪后缀时仍算同一条。"""
if not url:
return ""
try:
p = urllib.parse.urlsplit(str(url).strip())
path = (p.path or "").rstrip("/")
return urllib.parse.urlunsplit((p.scheme.lower(), p.netloc.lower(), path, "", ""))
except Exception:
return str(url).strip()
+80
View File
@@ -0,0 +1,80 @@
"""Unit tests for the extracted primitives (stdlib unittest, no deps)."""
import os
import sys
import unittest
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from monitor_core import (normalize_product_url, normalize_condition, parse_price,
strip_thumbnail_suffix, title_matches_keyword, iso_from_epoch, iso_now)
class UrlTests(unittest.TestCase):
def test_strips_progressive_thumbnail(self):
url = "https://media.example.com/abc.jpg_progressive_thumbnail"
self.assertEqual("https://media.example.com/abc.jpg", strip_thumbnail_suffix(url))
def test_strip_is_noop_without_suffix(self):
url = "https://media.example.com/abc.jpg"
self.assertEqual(url, strip_thumbnail_suffix(url))
def test_strip_keeps_empty_input(self):
self.assertEqual("", strip_thumbnail_suffix(""))
def test_normalize_drops_query_and_fragment(self):
a = "https://www.carousell.com.my/p/1234/?utm_source=x#top"
b = "https://WWW.Carousell.com.my/p/1234/"
self.assertEqual(normalize_product_url(a), normalize_product_url(b))
self.assertEqual("https://www.carousell.com.my/p/1234", normalize_product_url(a))
def test_normalize_handles_empty(self):
self.assertEqual("", normalize_product_url(None))
class PriceTests(unittest.TestCase):
def test_parses_thousands_separator(self):
self.assertEqual(1250.5, parse_price("RM 1,250.50"))
def test_parses_foreign_currency_prefix(self):
self.assertEqual(12.0, parse_price("S$ 12"))
def test_returns_none_for_text(self):
self.assertIsNone(parse_price("Free"))
self.assertIsNone(parse_price(""))
self.assertIsNone(parse_price(None))
def test_condition_aliases(self):
self.assertEqual("Brand new", normalize_condition("Brand New"))
self.assertEqual("Used", normalize_condition("used"))
self.assertIsNone(normalize_condition("refurbished"))
class KeywordTests(unittest.TestCase):
def test_case_insensitive_match(self):
self.assertTrue(title_matches_keyword("iPhone 13 PROTECTOR", ["protector"]))
def test_no_match(self):
self.assertFalse(title_matches_keyword("iPhone 13", ["samsung"]))
def test_empty_inputs(self):
self.assertFalse(title_matches_keyword("", ["x"]))
self.assertFalse(title_matches_keyword("x", []))
class TimeTests(unittest.TestCase):
def test_iso_now_shape(self):
self.assertRegex(iso_now(), r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$")
def test_epoch_conversion_is_utc(self):
self.assertEqual("2026-01-01 00:00:00", iso_from_epoch(1767225600))
def test_falsy_epoch(self):
self.assertIsNone(iso_from_epoch(0))
if __name__ == "__main__":
unittest.main()
+93
View File
@@ -0,0 +1,93 @@
# ============================================================
# Email Sync OAuth2 - Docker Compose Configuration
# ============================================================
# Copy this file to .env and edit your settings.
# ============================================================
# ------------------------------------------------------------
# Global settings
# ------------------------------------------------------------
# Number of accounts to sync
NUM_ACCOUNTS=2
# Sync interval in seconds (default: 21600 = 6 hours).
# Used when SYNC_CRON is empty.
SYNC_INTERVAL=21600
# Optional standard five-field cron expression. When set, it overrides
# SYNC_INTERVAL. Example: 0 */6 * * * (every six hours)
SYNC_CRON=
# Run once and exit (true/false)
ONCE=false
# Token and log directories inside container
TOKEN_DIR=/tokens
LOG_DIR=/var/log/imapsync
# ------------------------------------------------------------
# Account 1: Hotmail / Office 365 -> Mailcow (OAuth2)
# ------------------------------------------------------------
ACCOUNT_1_SOURCE_HOST=outlook.office365.com
ACCOUNT_1_SOURCE_USER=[email protected]
ACCOUNT_1_SOURCE_AUTH=oauth2
ACCOUNT_1_SOURCE_PROVIDER=office365
ACCOUNT_1_SOURCE_TOKEN=/tokens/user1_hotmail.token
ACCOUNT_1_DEST_HOST=mail.hoelee.com
ACCOUNT_1_DEST_USER=[email protected]
ACCOUNT_1_DEST_PASS=your_mailcow_password
# Delete emails on destination that don't exist on source (true/false)
ACCOUNT_1_DELETE=false
# Dry run - log what would happen without actually syncing (true/false)
ACCOUNT_1_DRY_RUN=false
# Extra imapsync options (optional)
ACCOUNT_1_EXTRA_OPTS=
# ------------------------------------------------------------
# Account 2: Any standard IMAP source (password authentication)
# ------------------------------------------------------------
ACCOUNT_2_SOURCE_HOST=imap.example.com
ACCOUNT_2_SOURCE_USER=[email protected]
ACCOUNT_2_SOURCE_AUTH=password
ACCOUNT_2_SOURCE_PASS=your_source_password
ACCOUNT_2_DEST_HOST=mail.hoelee.com
ACCOUNT_2_DEST_USER=[email protected]
ACCOUNT_2_DEST_PASS=your_mailcow_password
ACCOUNT_2_DELETE=false
ACCOUNT_2_DRY_RUN=false
ACCOUNT_2_EXTRA_OPTS=
# ------------------------------------------------------------
# Account 3+: copy an account block and increase NUM_ACCOUNTS.
# All ACCOUNT_N_* variables from .env are passed into the container.
# ------------------------------------------------------------
# ------------------------------------------------------------
# Optional SMTP notifications
# ------------------------------------------------------------
# none | batch_success | account_success | failure
# batch_success: one email after every fully successful sync batch
# account_success: one email for every successful account
# failure: one email when one or more accounts fail in a batch
NOTIFY_MODE=none
# Required only when NOTIFY_MODE is not none
SMTP_HOST=
SMTP_PORT=587
SMTP_USER=
SMTP_PASS=
SMTP_FROM=
# One or more comma-separated recipients
SMTP_TO=
# starttls (port 587), tls (implicit TLS, usually port 465), or none
SMTP_TLS=starttls
+83
View File
@@ -0,0 +1,83 @@
FROM alpine/git:2.47.2@sha256:062a01ad7a0eb17cff382bc5e26086b4d710e56dfdfdf001109a49b6d9bd378c AS imapsync-source
ARG IMAPSYNC_REV=93654c6025ff7814f983ab74dd300f9bed9282d9
RUN git clone https://github.com/imapsync/imapsync.git /src \
&& git -C /src checkout "$IMAPSYNC_REV" \
&& test "$(git -C /src rev-parse HEAD)" = "$IMAPSYNC_REV"
# Debian's own perl is used on purpose. The official perl:*-slim images ship a
# second interpreter in /usr/local/bin that shadows /usr/bin/perl on PATH but
# does not read Debian's @INC, so every libXXX-perl package installed below
# would be invisible to the interpreter that actually runs imapsync.
FROM debian:bookworm-slim
LABEL maintainer="Hoelee <[email protected]>"
LABEL description="Multi-account IMAP sync with OAuth2 support for Office 365, Hotmail, Outlook.com, and Gmail"
LABEL org.opencontainers.image.source="https://github.com/hoelee/email-sync-oauth2"
LABEL org.opencontainers.image.licenses="MIT"
# Package list follows upstream INSTALL.d/INSTALL.Debian.txt for the pinned
# revision, plus libdigest-hmac-perl (ships Digest::HMAC_SHA1) and the runtime
# tools this image needs (cron, msmtp).
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
perl \
libauthen-ntlm-perl \
libcgi-pm-perl \
libcrypt-openssl-rsa-perl \
libdata-uniqid-perl \
libdigest-hmac-perl \
libemail-address-perl \
libencode-imaputf7-perl \
libfile-copy-recursive-perl \
libfile-tail-perl \
libhtml-parser-perl \
libhttp-daemon-perl \
libhttp-daemon-ssl-perl \
libhttp-message-perl \
libio-socket-inet6-perl \
libio-socket-ssl-perl \
libio-tee-perl \
libjson-webtoken-perl \
libmail-imapclient-perl \
libmodule-scandeps-perl \
libnet-dns-perl \
libnet-server-perl \
libparse-recdescent-perl \
libproc-processtable-perl \
libreadonly-perl \
libregexp-common-perl \
libsys-meminfo-perl \
libterm-readkey-perl \
libtest-mockobject-perl \
libunicode-string-perl \
liburi-perl \
libwww-perl \
cron \
msmtp \
netcat-openbsd \
procps \
&& rm -rf /var/lib/apt/lists/*
# Install one immutable, verified upstream revision of imapsync and its current
# OAuth helper. The old helper URLs no longer exist upstream.
COPY --from=imapsync-source /src/imapsync /usr/local/bin/imapsync
COPY --from=imapsync-source /src/oauth2/oauth2_imap/oauth2_imap /usr/local/bin/oauth2_imap
RUN chmod +x /usr/local/bin/imapsync /usr/local/bin/oauth2_imap \
&& perl -c /usr/local/bin/imapsync \
&& perl -c /usr/local/bin/oauth2_imap \
&& imapsync --version
# Copy entrypoint
COPY sync.sh /sync.sh
RUN chmod +x /sync.sh && bash -n /sync.sh
# Health is liveness plus notification delivery. Sync freshness is exposed by
# accountN.last_success / accountN.last_failure files for the chosen schedule.
HEALTHCHECK --interval=5m --timeout=10s --start-period=60s --retries=3 \
CMD test -f "${LOG_DIR:-/var/log/imapsync}/.heartbeat" && \
test ! -f "${LOG_DIR:-/var/log/imapsync}/.notification_failed" && \
test "$(cat "${LOG_DIR:-/var/log/imapsync}/.heartbeat")" -gt "$(date -d '5 minutes ago' +%s)" || \
{ echo "Health check failed: daemon heartbeat is stale or SMTP notification delivery failed. Check container logs."; exit 1; }
ENTRYPOINT ["/sync.sh"]
+73
View File
@@ -0,0 +1,73 @@
.PHONY: build up down logs status health authorize sync sync-all shell clean
# Build the Docker image
build:
docker compose build
# Start the sync daemon
up:
docker compose up -d
@echo "Container started. Use 'make logs' to follow logs."
# Stop the container
down:
docker compose down
# Follow logs
logs:
docker logs -f email-sync-oauth2
# Show status of all accounts
status:
@echo "=== Container Status ==="
@docker inspect --format='Status: {{.State.Status}}' email-sync-oauth2 2>/dev/null || echo "Container not running"
@echo ""
@echo "=== Health Status ==="
@docker inspect --format='Health: {{.State.Health.Status}}' email-sync-oauth2 2>/dev/null || echo "No healthcheck"
@echo ""
@echo "=== Last Sync Times ==="
@for f in logs/*.last_success; do \
[ -f "$$f" ] && echo "$$(basename $$f .last_success): $$(date -d @$$(cat $$f) 2>/dev/null || echo 'unknown')"; \
done
@echo ""
@echo "=== Last Failures ==="
@for f in logs/*.last_failure; do \
[ -f "$$f" ] && echo "$$(basename $$f .last_failure): $$(date -d @$$(cat $$f) 2>/dev/null || echo 'unknown')"; \
done
# Check health
health:
@docker inspect --format='{{json .State.Health}}' email-sync-oauth2 | jq
# Authorize account (usage: make authorize ACCOUNT=1)
authorize:
@if [ -z "$(ACCOUNT)" ]; then \
echo "Usage: make authorize ACCOUNT=1"; \
exit 1; \
fi
docker compose run --rm imapsync authorize $(ACCOUNT)
# Force sync account (usage: make sync ACCOUNT=1)
sync:
@if [ -z "$(ACCOUNT)" ]; then \
echo "Usage: make sync ACCOUNT=1"; \
exit 1; \
fi
docker compose exec imapsync sync.sh sync $(ACCOUNT)
# Force a full batch now (all configured accounts)
sync-all:
docker compose exec imapsync sync.sh sync-all
# Enter container shell
shell:
docker compose exec imapsync sync.sh shell
# Clean up
clean:
docker compose down -v
rm -rf logs/*.log logs/*.last_* logs/.heartbeat logs/.notification_failed
# One-shot sync (build, run once, exit)
once:
ONCE=true docker compose up --build --abort-on-container-exit
+13
View File
@@ -0,0 +1,13 @@
# shell-sync
Multi-account IMAP sync driven by `mbsync`, with OAuth2 token refresh for
providers that no longer accept plain passwords. Extracted from
`hoelee/email-sync-oauth2`.
The entrypoint refreshes each account's token, regenerates the `mbsyncrc` from
environment variables, then runs incremental sync on a timer. Credentials come
from the environment only - see `.env.example`.
```
make build && make run
```
+427
View File
@@ -0,0 +1,427 @@
#!/bin/bash
set -Eeuo pipefail
# IMAP Sync Manager - multi-account OAuth2 and password authentication.
TOKEN_DIR="${TOKEN_DIR:-/tokens}"
LOG_DIR="${LOG_DIR:-/var/log/imapsync}"
PID_DIR="${PID_DIR:-/tmp/imapsync}"
HEARTBEAT_FILE="${LOG_DIR}/.heartbeat"
NUM_ACCOUNTS="${NUM_ACCOUNTS:-1}"
SYNC_INTERVAL="${SYNC_INTERVAL:-21600}" # six hours
SYNC_CRON="${SYNC_CRON:-}"
ONCE="${ONCE:-false}"
# Notifications are disabled unless NOTIFY_MODE is explicitly set.
# Valid modes: none, batch_success, account_success, failure.
NOTIFY_MODE="${NOTIFY_MODE:-none}"
SMTP_HOST="${SMTP_HOST:-}"
SMTP_PORT="${SMTP_PORT:-587}"
SMTP_USER="${SMTP_USER:-}"
SMTP_PASS="${SMTP_PASS:-}"
SMTP_FROM="${SMTP_FROM:-}"
SMTP_TO="${SMTP_TO:-}"
SMTP_TLS="${SMTP_TLS:-starttls}"
NOTIFICATION_FAILURE_FILE="${LOG_DIR}/.notification_failed"
NOTIFICATION_LOG="${LOG_DIR}/notification.log"
mkdir -p "$LOG_DIR" "$PID_DIR" "$TOKEN_DIR"
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"
}
get_var() {
local varname="$1"
echo "${!varname:-}"
}
oauth_authorization_invalid() {
local logfile="$1"
tail -n 200 "$logfile" 2>/dev/null | grep -Eqi \
'invalid_grant|expired.*(token|credential)|token.*expired|refresh token.*(expired|revoked|invalid)|authorization.*(expired|revoked)|AADSTS700082|AADSTS700084|AUTHENTICATE failed|authentication.*failed|authentication unsuccessful|invalid credentials'
}
log_oauth_authorization_guidance() {
local i="$1"
local provider="$2"
local logfile="$3"
if oauth_authorization_invalid "$logfile"; then
log "Account $i: OAuth2 authorization is expired, revoked, or rejected by $provider. Reauthorize with: docker compose run --rm imapsync authorize $i"
log "Account $i: After reauthorization, run immediately with: docker compose exec imapsync sync.sh sync $i"
fi
}
validate_settings() {
if ! [[ "$NUM_ACCOUNTS" =~ ^[1-9][0-9]*$ ]]; then
log "Configuration error: NUM_ACCOUNTS must be a positive integer"
return 1
fi
if [ -z "$SYNC_CRON" ] && ! [[ "$SYNC_INTERVAL" =~ ^[1-9][0-9]*$ ]]; then
log "Configuration error: SYNC_INTERVAL must be a positive number of seconds"
return 1
fi
case "$NOTIFY_MODE" in
none|batch_success|account_success|failure) ;;
*)
log "Configuration error: NOTIFY_MODE must be none, batch_success, account_success, or failure"
return 1
;;
esac
if [ "$NOTIFY_MODE" != "none" ]; then
if [ -z "$SMTP_HOST" ] || [ -z "$SMTP_FROM" ] || [ -z "$SMTP_TO" ]; then
log "Configuration error: SMTP_HOST, SMTP_FROM, and SMTP_TO are required when notifications are enabled"
return 1
fi
if ! [[ "$SMTP_PORT" =~ ^[1-9][0-9]*$ ]]; then
log "Configuration error: SMTP_PORT must be a valid port number"
return 1
fi
if { [ -n "$SMTP_USER" ] && [ -z "$SMTP_PASS" ]; } || { [ -z "$SMTP_USER" ] && [ -n "$SMTP_PASS" ]; }; then
log "Configuration error: SMTP_USER and SMTP_PASS must either both be set or both be empty"
return 1
fi
case "$SMTP_TLS" in starttls|tls|none) ;; *)
log "Configuration error: SMTP_TLS must be starttls, tls, or none"
return 1
;;
esac
fi
}
send_notification() {
local subject="$1"
local body="$2"
local config
local -a recipients
if [ "$NOTIFY_MODE" = "none" ]; then
return 0
fi
config="$(mktemp "${PID_DIR}/msmtp.XXXXXX")"
chmod 600 "$config"
{
printf 'defaults\n'
printf 'host %s\n' "$SMTP_HOST"
printf 'port %s\n' "$SMTP_PORT"
printf 'from %s\n' "$SMTP_FROM"
if [ -n "$SMTP_USER" ]; then
printf 'auth on\nuser %s\npassword %s\n' "$SMTP_USER" "$SMTP_PASS"
else
printf 'auth off\n'
fi
case "$SMTP_TLS" in
starttls) printf 'tls on\ntls_starttls on\n' ;;
tls) printf 'tls on\ntls_starttls off\n' ;;
none) printf 'tls off\n' ;;
esac
} > "$config"
IFS=',' read -r -a recipients <<< "$SMTP_TO"
if printf 'From: %s\nTo: %s\nSubject: %s\n\n%s\n' "$SMTP_FROM" "$SMTP_TO" "$subject" "$body" \
| msmtp --file="$config" "${recipients[@]}" >> "$NOTIFICATION_LOG" 2>&1; then
rm -f "$config" "$NOTIFICATION_FAILURE_FILE"
log "Notification sent: $subject"
return 0
fi
rm -f "$config"
printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$subject" > "$NOTIFICATION_FAILURE_FILE"
log "Notification delivery failed; container will remain unhealthy until a notification is sent successfully. Check $NOTIFICATION_LOG"
return 1
}
source_oauth_provider() {
case "$1" in
office365|outlook|hotmail) echo "office365" ;;
gmail|google) echo "gmail" ;;
*) return 1 ;;
esac
}
sync_account() {
local i="$1"
local src_host="$(get_var "ACCOUNT_${i}_SOURCE_HOST")"
local src_user="$(get_var "ACCOUNT_${i}_SOURCE_USER")"
local src_auth="$(get_var "ACCOUNT_${i}_SOURCE_AUTH")"
local src_pass="$(get_var "ACCOUNT_${i}_SOURCE_PASS")"
local src_token="$(get_var "ACCOUNT_${i}_SOURCE_TOKEN")"
local src_provider="$(get_var "ACCOUNT_${i}_SOURCE_PROVIDER")"
local dest_host="$(get_var "ACCOUNT_${i}_DEST_HOST")"
local dest_user="$(get_var "ACCOUNT_${i}_DEST_USER")"
local dest_pass="$(get_var "ACCOUNT_${i}_DEST_PASS")"
local delete_opt="$(get_var "ACCOUNT_${i}_DELETE")"
local dry_run="$(get_var "ACCOUNT_${i}_DRY_RUN")"
local extra_opts="$(get_var "ACCOUNT_${i}_EXTRA_OPTS")"
local logfile="${LOG_DIR}/account${i}.log"
local pidfile="${PID_DIR}/account${i}.pid"
local oauth_provider
local oauth_log
local oauth_authorization_detected=false
local sync_exit
local -a args
SYNC_ACCOUNT_RESULT="skipped"
if [ -z "$src_host" ] && [ -z "$dest_host" ]; then
log "Account $i: SKIP (not configured)"
return 0
fi
if [ -z "$src_host" ] || [ -z "$src_user" ] || [ -z "$dest_host" ] || [ -z "$dest_user" ] || [ -z "$dest_pass" ]; then
log "Account $i: CONFIGURATION FAILED (source host/user and destination host/user/password are required)"
SYNC_ACCOUNT_RESULT="failure"
echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure"
return 1
fi
if [ -f "$pidfile" ]; then
local old_pid
old_pid="$(cat "$pidfile")"
if kill -0 "$old_pid" 2>/dev/null; then
log "Account $i: SKIP (already running, PID $old_pid)"
return 0
fi
fi
echo $$ > "$pidfile"
log "Account $i: SYNC START - $src_user ($src_host) -> $dest_user ($dest_host)"
args=(
--host1 "$src_host" --user1 "$src_user" --ssl1
--host2 "$dest_host" --user2 "$dest_user" --password2 "$dest_pass" --ssl2
--noauthmd5
)
case "$src_auth" in
oauth2)
if ! oauth_provider="$(source_oauth_provider "$src_provider")"; then
log "Account $i: CONFIGURATION FAILED (OAuth2 provider must be office365, outlook, hotmail, gmail, or google)"
SYNC_ACCOUNT_RESULT="failure"
echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure"
rm -f "$pidfile"
return 1
fi
if [ -z "$src_token" ]; then
log "Account $i: CONFIGURATION FAILED (ACCOUNT_${i}_SOURCE_TOKEN is required for OAuth2)"
SYNC_ACCOUNT_RESULT="failure"
echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure"
rm -f "$pidfile"
return 1
fi
if [ ! -s "$src_token" ]; then
log "Account $i: OAuth2 token is missing. Authorize with: docker compose run --rm imapsync authorize $i"
SYNC_ACCOUNT_RESULT="failure"
echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure"
rm -f "$pidfile"
return 1
fi
# The helper prints access and refresh tokens. Keep that output in a
# short-lived, root-only file instead of the mounted account log.
oauth_log="$(mktemp "${PID_DIR}/oauth.XXXXXX")"
chmod 600 "$oauth_log"
# The upstream helper opens an interactive browser flow when refresh
# fails. A scheduled container must never wait indefinitely for that.
timeout --kill-after=5s 90s oauth2_imap --provider "$oauth_provider" --application imapsync --token_file "$src_token" "$src_user" > "$oauth_log" 2>&1 || true
if oauth_authorization_invalid "$oauth_log"; then
log_oauth_authorization_guidance "$i" "$src_provider" "$oauth_log"
oauth_authorization_detected=true
fi
rm -f "$oauth_log"
if [ ! -s "$src_token" ]; then
log "Account $i: OAuth2 token refresh or authorization failed"
log_oauth_authorization_guidance "$i" "$src_provider" "$logfile"
SYNC_ACCOUNT_RESULT="failure"
echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure"
rm -f "$pidfile"
return 1
fi
args+=(--oauthaccesstoken1 "$src_token")
;;
password)
if [ -z "$src_pass" ]; then
log "Account $i: CONFIGURATION FAILED (ACCOUNT_${i}_SOURCE_PASS is required for password authentication)"
SYNC_ACCOUNT_RESULT="failure"
echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure"
rm -f "$pidfile"
return 1
fi
args+=(--password1 "$src_pass")
;;
*)
log "Account $i: CONFIGURATION FAILED (ACCOUNT_${i}_SOURCE_AUTH must be oauth2 or password)"
SYNC_ACCOUNT_RESULT="failure"
echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure"
rm -f "$pidfile"
return 1
;;
esac
[ "$delete_opt" = "true" ] && args+=(--delete2)
[ "$dry_run" = "true" ] && args+=(--dry)
if [ -n "$extra_opts" ]; then
# Intentional option splitting: this variable supplies extra CLI flags.
# shellcheck disable=SC2206
args+=($extra_opts)
fi
# Capture the real exit status. Reading $? after an `if` block returns the
# status of the `if` itself (always 0), which silently reported every
# failure as exit 0 and let sync_all treat it as success.
sync_exit=0
imapsync "${args[@]}" >> "$logfile" 2>&1 || sync_exit=$?
if [ "$sync_exit" -eq 0 ]; then
log "Account $i: SYNC OK"
echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_success"
SYNC_ACCOUNT_RESULT="success"
rm -f "$pidfile"
return 0
fi
log "Account $i: SYNC FAILED (exit $sync_exit)"
echo "$(date +%s)" > "${LOG_DIR}/account${i}.last_failure"
if [ "$src_auth" = "oauth2" ] && [ "$oauth_authorization_detected" = "false" ]; then
log_oauth_authorization_guidance "$i" "$src_provider" "$logfile"
fi
SYNC_ACCOUNT_RESULT="failure"
rm -f "$pidfile"
return "$sync_exit"
}
sync_all() {
local i
local configured=0
local failures=0
local notification_failures=0
local successes=""
local failed_accounts=""
log "=== Sync cycle start ==="
for ((i = 1; i <= NUM_ACCOUNTS; i++)); do
if sync_account "$i"; then
if [ "$SYNC_ACCOUNT_RESULT" = "success" ]; then
configured=$((configured + 1))
successes="${successes}${successes:+, }${i}"
if [ "$NOTIFY_MODE" = "account_success" ]; then
send_notification "IMAP sync succeeded for account $i" "Account $i completed successfully at $(date '+%Y-%m-%d %H:%M:%S')." || notification_failures=1
fi
fi
else
configured=$((configured + 1))
failures=$((failures + 1))
failed_accounts="${failed_accounts}${failed_accounts:+, }${i}"
fi
done
if [ "$NOTIFY_MODE" = "batch_success" ] && [ "$configured" -gt 0 ] && [ "$failures" -eq 0 ]; then
send_notification "IMAP sync batch succeeded" "All configured accounts completed successfully at $(date '+%Y-%m-%d %H:%M:%S'): $successes." || notification_failures=1
fi
if [ "$NOTIFY_MODE" = "failure" ] && [ "$failures" -gt 0 ]; then
send_notification "IMAP sync batch failed" "Sync failed for account(s) $failed_accounts at $(date '+%Y-%m-%d %H:%M:%S'). Check ${LOG_DIR}/accountN.log for details." || notification_failures=1
fi
log "=== Sync cycle complete (success: ${successes:-none}; failed: ${failed_accounts:-none}) ==="
[ "$failures" -eq 0 ] && [ "$notification_failures" -eq 0 ]
}
start_heartbeat() {
echo "$(date +%s)" > "$HEARTBEAT_FILE"
while true; do
echo "$(date +%s)" > "$HEARTBEAT_FILE"
sleep 60
done &
HEARTBEAT_PID=$!
}
run_cron_scheduler() {
local wrapper="${PID_DIR}/cron-sync-all.sh"
local crontab_file="${PID_DIR}/sync.crontab"
# Cron starts commands with a minimal environment. Preserve this container's
# configuration in a root-only Bash wrapper so arbitrary ACCOUNT_N_* values work.
{
printf '#!/bin/bash\n'
export -p
printf 'exec /sync.sh sync-all\n'
} > "$wrapper"
chmod 700 "$wrapper"
printf '%s %s >> /proc/1/fd/1 2>&1\n' "$SYNC_CRON" "$wrapper" > "$crontab_file"
if ! crontab "$crontab_file"; then
log "Configuration error: SYNC_CRON is not a valid cron expression: $SYNC_CRON"
return 1
fi
log "Starting cron schedule: $SYNC_CRON"
cron -f &
CRON_PID=$!
wait "$CRON_PID"
}
run_once() {
log "Running in ONCE mode"
local status=0
sync_all || status=$?
log "One-shot sync complete"
return "$status"
}
run_daemon() {
log "Starting daemon mode (accounts: $NUM_ACCOUNTS)"
start_heartbeat
trap 'kill "${HEARTBEAT_PID:-}" "${CRON_PID:-}" 2>/dev/null || true' EXIT
if [ -n "$SYNC_CRON" ]; then
run_cron_scheduler
return
fi
while true; do
sync_all || true
log "Sleeping ${SYNC_INTERVAL}s before the next sync cycle"
sleep "$SYNC_INTERVAL"
done
}
case "${1:-}" in
sync)
shift
validate_settings
sync_account "${1:-1}"
;;
sync-all)
validate_settings
sync_all
;;
authorize)
shift
i="${1:-1}"
src_user="$(get_var "ACCOUNT_${i}_SOURCE_USER")"
src_token="$(get_var "ACCOUNT_${i}_SOURCE_TOKEN")"
src_provider="$(get_var "ACCOUNT_${i}_SOURCE_PROVIDER")"
validate_settings
if ! provider="$(source_oauth_provider "$src_provider")" || [ -z "$src_user" ] || [ -z "$src_token" ]; then
log "Account $i: authorization requires a supported OAuth2 provider, source user, and token path"
exit 1
fi
log "Manual authorize: $src_user"
exec oauth2_imap --startover --provider "$provider" --application imapsync --token_file "$src_token" "$src_user"
;;
shell|bash|sh)
exec /bin/bash
;;
imapsync)
shift
exec imapsync "$@"
;;
*)
validate_settings
if [ "$ONCE" = "true" ]; then
run_once
else
run_daemon
fi
;;
esac
+1 -1
View File
@@ -1,4 +1,4 @@
package botfilter
package traefik_botfilter
import (
"net"