Delete PLAN.md

This commit is contained in:
2026-10-29 07:37:45 +00:00
parent d2f160e0f3
commit 3b25aa6cf8
-295
View File
@@ -1,295 +0,0 @@
# Azzamo Noteguard: implementation plan
Scope: write policy only (`noteguard` with no args). The read side (`noteguard read`, `src/readpolicy.rs`, `src/readfilters/`) is out of scope. Nothing in this plan changes behavior for an existing `noteguard.toml`: every new key is optional and every default equals today's hard-coded value.
Approach (ponytail ladder): reuse what exists before writing anything new. That means the `message` key pattern ratelimit and nscript already use, the global worker pattern from `src/cloudflare.rs`, the `ureq` that is already a dependency, and the std `RwLock<Arc<T>>`. No new crates are planned.
---
## What I found
### Pipeline (your understanding is correct, with two additions)
- `src/main.rs:74-95` `Noteguard::run`: `Accept` sets `mout` and `continue`s (81-84). `Reject` and `ShadowReject` `return` right away (85-90). So a pipeline filter is a gate and can never bypass a later filter. Any "premium skips X" must live inside filter X. **Confirmed.**
- Addition 1: the final result is the **last** filter's `Accept` OutputMessage (`main.rs:94`), not a fresh one. Today every Accept carries `msg: None`, so this has no visible effect. New filters must keep returning `Accept` with `None`.
- Addition 2: strfry ignores `msg` on `shadowReject` (the client sees OK true). So `content` (shadow only, `content.rs:217,232`) needs no message key.
### Construction and startup
- `main.rs:44-53` `register_filter<F: NoteFilter + Default + DeserializeOwned>`: a filter is built by `toml::Value::try_into::<F>()`. There is **no init hook and no shared context** passed to constructors. Startup work either runs inside a custom `Deserialize` (the pattern in `blacklist.rs:21-38` and `ban.rs:257-267`) or in `main` before `load_config`.
- `main.rs:99-117` `load_config` panics on a missing filter table (106) and on an unknown filter name (112). Config errors therefore already crash at startup, and strfry then rejects writes. Keep this behavior.
- `main.rs:369-383`: the config is parsed once, then `load_config`, then `cloudflare::init`. A new `sources::init` must run **before** `load_config` so filters can resolve source names while they deserialize.
- `filter_note(&mut self, ...)` (`src/note_filter.rs:13`) runs synchronously in one long-lived process per strfry ingester thread. So there are N processes per relay, each with its own state, and each will run its own fetch thread.
- `src/cloudflare.rs:364-410` is the in-tree precedent for this work: a process-global `OnceLock`, a background thread, a token from an env var, `ureq` with a timeout, and a trait seam (`CfApi`, 106-117) so tests need no network.
### Hard-coded rejection strings today
| Where | String | Configurable now? |
|---|---|---|
| `blacklist.rs:62` | `blocked: pubkey/ip is blacklisted` | no |
| `whitelist.rs:111` | `blocked: pubkey/ip not on the whitelist` | no |
| `kinds.rs:137` | `blocked: note kind is not allowed here` | per kind only (`messages` table) |
| `protected_events.rs:162` | `blocked: event marked as protected` | no |
| `ratelimit.rs:97` | `rate-limited: you are noting too much` | yes, `message` |
| `ban.rs:275` | `banned: too many violations, try again later` | yes, `ban_message` |
| `nscript.rs:23,54` | none by default | yes, `message` |
| `main.rs:408` | `invalid strfry write policy input` | no (protocol error, leave as is) |
The established pattern is a single `message` key (ratelimit, nscript) plus the kinds `messages` table. Use that pattern everywhere.
### Other facts
- `ratelimit.rs:34-50`: the IP whitelist is checked first, then the IP ban. A premium check goes between them.
- `content.rs:216-226`: the IP-ban check comes before the word match, and words are normalized lazily once (`normalized: Option<Vec<String>>`). That has to become "re-normalize when the remote snapshot changes".
- `blacklist.rs:64-65` and `whitelist.rs:96-97` use `Vec::contains`, which is O(n). That is fine for static lists. Remote lists use a `HashMap`.
- `Cargo.toml`: `ureq = "2"` is optional behind `cloudflare` and locked at 2.12.1 with rustls. Rust 1.85, so `OnceLock` and let-else are available.
- `readpolicy.rs:69-71` `FileConfig` only reads `readpolicy` and does not deny unknown fields, so a new top-level `[sources]` table is invisible to the read side. **The only shared code is `lib.rs:22` `config_path()` and the config file itself.** Later, the read side's `read_bandwidth.whitelist` could use the premium source, but that is not in this plan.
- The repo `noteguard.toml:1` pipeline contains `whitelist`. On the free relay that would reject everyone, so the free example config must drop it.
- Test naming bug: `main.rs:506` `test_run_filters_shadow_reject` asserts `Reject`. Rename it in Phase 0.
### Design review (where I differ from the brief)
1. **No separate `premium_gate` filter.** "Accept only pubkeys in set S" is what `whitelist` already does. Extend `whitelist` with `pubkey_sources = [...]`. The premium gate is then `whitelist` + the premium source, and the optional NIP-05 filter is `whitelist` + a source with `format = "nip05"`. This gives one gate, one unavailable policy and fewer lines. (Decision D7 if you want a distinct name.)
2. **One pubkey type for everything.** Premium, pubkey blacklist and NIP-05 all parse to `PubkeySet = HashMap<hex, Option<expires_at>>`. The blacklist then gets temporary bans for free (expiry honored).
3. **Sources declared once at the top level** (`[sources.<name>]`, like `[cloudflare]`), referenced by name from filters. One store per process is shared by every filter that names it.
4. **Content re-normalizes on the note path** when the snapshot `Arc` changes (`Arc::ptr_eq`). That is once per reload and only milliseconds, and it keeps the source module generic.
5. The first load is **synchronous at startup**, bounded by the timeout, so a fail-closed gate does not reject the first notes after every restart.
6. **nscript/WASM guests were considered and rejected for this work:**
- Guests have no network or file access. Their only host imports are note accessors plus `owner` and `follows` (`src/nscript.rs:133-200`). Fetching, reload, cache and the token would still be host code, which is most of P2 to P4.
- Each note runs in a fresh `Store` (`nscript.rs:102-111`), so guests keep no state between notes and cannot rate limit.
- The guest only returns a verdict. A pipeline Accept cannot exempt a note from `ratelimit` or `content`, so the premium exemptions still have to be native.
- nscript is hard-coded to fail open (`filters/nscript.rs:44-46,56-59`), but the premium gate must fail closed.
- Only one `nscript` entry fits per pipeline, there is a single `message`, and the feature is an experimental spike with a heavy wasmtime dependency.
Possible later step, out of scope here: a host import such as `source_contains(name, pubkey)` would let per-npub guests reuse these sources.
---
## Phase dependency graph
```
P0 baseline
|-- P1 custom messages ------------------------------+
|-- P2 source model + parsers |
|-- P3 source runtime (file, reload, cache, [sources])
|-- P4 HTTP transport (feature remote) |
|-- P5 blacklist remote pubkeys <---------+ (after P1: same file)
|-- P6 ratelimit premium exemption
|-- P7 content remote words + premium IP-ban skip
|-- P8 premium gate via whitelist <--------+ (after P1: same file)
|
P4..P8 --> P9 example configs, README, deployment checklist
P8 -----> P10 NIP-05 format (optional, off by default)
```
- Can run in parallel: P1 with P2/P3. P4, P5, P6, P7 and P8 with each other once P3 lands (and P1 for P5/P8). They touch different `src/filters/*.rs` files, but all add a README section, so merge them one at a time.
- Blocking: P2 blocks P3, and P3 blocks P4 to P8. P9 needs P4 to P8. P10 needs P8.
- Production value arrives at P9 (needs P4 for HTTP). P5 to P8 are testable with file sources alone.
---
## Decisions I need from you (recommended default in bold)
- **D1 API response shapes.** **Premium and blacklist: a JSON array whose items are either a hex string or `{"pubkey": "<hex>", "expires_at": <unix secs or null>}`, optionally wrapped as `{"pubkeys": [...]}`. Words: an array of strings, optionally `{"words": [...]}`.** Unknown object fields are ignored. Please confirm what the Azzamo API actually returns, or send a sample.
- **D2 Key and time formats.** **Hex only: lowercased and validated as 64 hex chars, with npub and malformed entries skipped and counted in the log (no bech32 dependency). `expires_at` as integer unix seconds (no ISO 8601, no chrono). Expired means `now >= expires_at`, with no grace period.**
- **D3 Gate when no list could be loaded and there is no cache.** **Fail closed: visible Reject with its own message (`blocked: membership list unavailable, try again shortly`).** The disk cache makes this rare. The alternative `unavailable = "accept"` lets everyone write during the outage.
- **D4 Rate limit on premium relays.** **On, as a runaway-client guard: `posts_per_minute = 60`, no `ban_after`, no premium exemption** (everyone there is premium, so an exemption would make it a no-op). Off is also defensible.
- **D5 Blacklisted pubkeys: visible or shadow reject.** **Visible Reject (today's behavior).** Shadow hides detection from spammers but confuses false positives. If you want shadow, it is one `shadow = true` key on blacklist.
- **D6 Premium author whose note matches a blocked word.** **Shadow-reject the note but do not strike the IP**, so a premium user does not get the shared IP banned for others.
- **D7 Gate filter shape.** **Extend `whitelist` (`pubkey_sources`)** rather than adding `premium_gate`. Say so if you want the separate name for readability in the config.
- **D8 HTTP feature flag.** **New non-default feature `remote = ["ureq"]`. Production builds use `--features remote,cloudflare`.** A config with an `http(s)` source in a build without the feature fails at startup with a clear message.
- **D9 Non-IP sources on premium relays** (strfry router/stream `sourceType` other than IP4/IP6). **Gate them like anything else.** If relay, us and asia sync with each other through strfry router, an expired member's old notes stop syncing. Confirm that is acceptable.
- **D10 Zap receipts (kind 9735) and NIP-17 gift wraps (kind 1059) to premium users.** These are signed by non-premium keys, so the gate rejects them. **Out of scope at first, but documented.** An `exempt_kinds` key on whitelist is a small add if you want it.
- **D11 Timing defaults.** **`reload_secs = 300` (minimum 30), `timeout_secs = 10`, `max_bytes = 10 MiB`.** API load is roughly (relays x ingester threads x sources) / reload_secs.
- **D12 Staleness.** **Keep the last good copy indefinitely and log its age on every failed reload.** Expiries still apply to the stale copy, so a premium user cannot outlive `expires_at`. New payments and revocations do wait for the API to recover. A `max_stale_secs` key is possible later.
---
## Rollback
Every phase ships as a new binary, plus at most a config change that is backward compatible.
1. Before each deploy, on each relay: `cp noteguard noteguard.prev` and `cp noteguard.toml noteguard.toml.prev`.
2. Install with an atomic rename (`install -m755 new /path/noteguard.new && mv /path/noteguard.new /path/noteguard`). Never `cp` over the running binary.
3. Roll back by restoring both `.prev` files with `mv`, then make strfry restart the plugin. strfry relaunches the write plugin when the plugin file's mtime changes, so the `mv` usually suffices. **Verify this on your strfry version.** If unsure, restart strfry.
4. noteguard reads its config only at startup. After a **config-only** rollback, `touch` the binary or restart strfry.
5. Phases P0 to P8 are inert until a config references the new keys, so rolling back the config alone undoes the behavior. The cache files (P3) are safe to leave behind.
6. Order: deploy to the free relay first, then one premium relay (asia), then the rest, and watch the logs for one reload interval between steps.
---
## Phase 0: Baseline golden tests
1. **Goal:** freeze today's observable output so every later phase proves it changed nothing.
2. **Files:** add `tests/golden.rs`, `test/golden.toml` (a copy of today's write-side `noteguard.toml`, without `[readpolicy]` and with the whitelist pubkey kept) and `test/golden.expected`. Change `src/main.rs` (test rename only).
3. **Tasks:**
1. Run `cargo test` and record the pass count in the PR description.
2. Write `tests/golden.rs`: spawn `env!("CARGO_BIN_EXE_noteguard")` with `NOTEGUARD_CONFIG=test/golden.toml`, pipe `test/inputs`, and compare stdout line by line to `test/golden.expected`. Generate the expected file once from the current binary and review it by hand.
3. Add exact-string unit tests for each default message in the table above (blacklist, whitelist, kinds default, protected_events, ratelimit default, ban default).
4. Rename `test_run_filters_shadow_reject` to `test_protected_events_reject`.
4. **Config keys:** none.
5. **Tests:** `golden_output_matches`, `default_message_blacklist`, `default_message_whitelist`, `default_message_kinds_fallback`, `default_message_protected`, `default_message_ratelimit`, `default_message_ban`.
6. **Done when:** `cargo test` is green, `cargo test --features cloudflare` is green, `git diff --stat src/filters` is empty, and the golden file is committed.
7. **Risks:** ratelimit is time based. All inputs arrive within one second, so `diff.as_secs()` is 0 and the output is deterministic. If it flakes, drop `ratelimit` from `golden.toml` and cover it with unit tests instead.
## Phase 1: Custom rejection messages
1. **Goal:** every visible rejection string becomes configurable through a `message` key, with defaults byte for byte identical.
2. **Files:** `src/filters/blacklist.rs`, `src/filters/whitelist.rs`, `src/filters/kinds.rs`, `src/filters/protected_events.rs`, `README.md`.
3. **Tasks:**
1. Add `message: Option<String>` to `BlacklistConfig`/`Blacklist`, `Whitelist`, `Kinds` and `ProtectedEvents`, read with `.as_deref().unwrap_or("<today's string>")` as `ratelimit.rs:94-97` does.
2. Kinds lookup order: `messages[kind]`, then `message`, then the default.
3. Document `message` for every filter in the README, including the existing `ratelimit.message`, `ban_message` and `nscript.message`. Note that `content` has no message because a shadow reject sends none.
4. **Config keys:** `filters.{blacklist,whitelist,kinds,protected_events}.message`, all optional, defaulting to today's strings.
5. **Tests:** `blacklist_custom_message`, `whitelist_custom_message`, `kinds_message_fallback_order`, `protected_events_custom_message`, plus the P0 default tests unchanged.
6. **Done when:** `cargo test` is green, the golden test passes unchanged, and `cargo test --features cloudflare` is green.
7. **Risks:** none significant. `ProtectedEvents` stops being an empty struct, so confirm that an empty `[filters.protected_events]` table still parses (it does with `Option`).
## Phase 2: Source data model and parsers (pure, no I/O)
1. **Goal:** the types and parsers every remote list uses, fully unit tested without any threads, files or network.
2. **Files:** add `src/sources/mod.rs` and `src/sources/parse.rs`. Change `src/lib.rs` (`pub mod sources;`).
3. **Tasks:**
1. `PubkeySet { map: HashMap<String, Option<u64>> }` with `is_active(&self, pubkey, now_unix) -> bool`. The expiry is checked on every lookup.
2. `WordList(Vec<String>)`.
3. `parse_pubkeys(&[u8]) -> Result<(PubkeySet, Skipped)>`: accepts the D1 shapes, lowercases, validates 64 hex chars, and counts skipped entries. Duplicates keep the latest expiry, and `null` means no expiry.
4. `parse_words(&[u8])`: drops empty strings and trims.
5. `Format` enum (`pubkeys`, `words`) deserialized from config. `nip05` is added in P10.
4. **Config keys:** none yet.
5. **Tests:** `parses_plain_hex_array`, `parses_object_array_with_expiry`, `parses_wrapped_object`, `mixed_strings_and_objects`, `uppercase_normalized`, `invalid_and_npub_skipped_and_counted`, `duplicate_keeps_latest_expiry`, `null_expiry_never_expires`, `expired_is_inactive_at_boundary`, `words_array_and_wrapped`, `garbage_json_is_error`.
6. **Done when:** `cargo test sources::` and `cargo test` are green, and nothing outside `src/sources/` and `lib.rs` has changed.
7. **Risks:** the real API shape (D1). Keep the parser shape-tolerant so a minor API change does not need a release.
## Phase 3: Source runtime (local file source, reload, cache, `[sources]` wiring)
1. **Goal:** named sources declared in config, loaded at startup, reloaded in the background, swapped atomically, with the last good copy kept and an optional disk cache. Local files only in this phase.
2. **Files:** add `src/sources/runtime.rs`. Change `src/sources/mod.rs` and `src/main.rs` (`Config.sources`, init order).
3. **Tasks:**
1. `SourceConfig { url, format, token_env, reload_secs, timeout_secs, max_bytes, cache_path }`. In this phase `url` accepts `file:///abs/path` or a bare path.
2. `Source<T> { snapshot: RwLock<Option<Arc<T>>>, ... }`. `None` means never loaded. `get() -> Option<Arc<T>>` is a cheap clone on the note path.
3. `load_once()`: read with a `max_bytes` cap (`Read::take(max+1)` and reject if over), parse, and on success swap the snapshot and write the cache (`<cache_path>.tmp.<pid>` then `rename`, which is safe with N processes). On failure, keep the old snapshot and `warn!` the error and its age.
4. Startup per source: `load_once`. If that fails and `cache_path` exists, parse the cache. Otherwise leave it as never loaded and log `error!`.
5. A single background thread per process iterates over sources on their `reload_secs` schedule (clamped to at least 30), modeled on the `cloudflare.rs` worker.
6. Registry: `static SOURCES: OnceLock<HashMap<String, Arc<AnySource>>>`. `sources::declare(&HashMap<String, SourceConfig>)` registers the sources without loading them, and `sources::start()` does the initial load and spawns the thread. `pubkey_source(name)` and `word_source(name)` return a typed `Arc` or a format-mismatch error.
7. `main.rs`: add `#[serde(default)] sources: HashMap<String, SourceConfig>` to `Config`, and call `declare` and then `start` **before** `load_config`.
8. Tests use unique source names per test, because the registry is global and tests run in parallel. Files go in `std::env::temp_dir()`, as `shm.rs:575` does.
4. **Config keys:** `[sources.<name>]` with `url` (required), `format` (required: `pubkeys` or `words`), `reload_secs` (300, minimum 30), `timeout_secs` (10), `max_bytes` (10485760), `cache_path` (unset means no cache), `token_env` (unset, used in P4).
5. **Tests:** `file_source_loads_at_start`, `reload_picks_up_change`, `bad_reload_keeps_last_good`, `oversize_rejected_keeps_last_good`, `cache_written_after_success`, `cache_used_when_source_missing_at_start`, `never_loaded_is_none`, `format_mismatch_is_error`, `reload_interval_clamped`, `config_without_sources_parses` (backward compatible).
6. **Done when:** `cargo test` is green, the golden test is unchanged, and a config without `[sources]` behaves identically: the golden test proves that.
7. **Risks:** reload tests need a short interval. Expose a test-only interval or call `reload_due(now)` directly instead of sleeping. Process-global state in tests: keep the registry additive and keyed by unique names.
## Phase 4: HTTP(S) transport with bearer token
1. **Goal:** `http://` and `https://` source URLs fetched with `ureq`, behind the `remote` feature.
2. **Files:** `Cargo.toml` (feature `remote = ["ureq"]`), `src/sources/runtime.rs` (transport), `src/sources/http.rs` (new, `#[cfg(feature = "remote")]`).
3. **Tasks:**
1. A `Transport` trait seam (`fetch(&SourceConfig) -> Result<Vec<u8>>`), as `CfApi` does, so the runtime logic stays testable.
2. `HttpTransport`: a `ureq::AgentBuilder` with connect and read timeouts from `timeout_secs`. `Authorization: Bearer $TOKEN` when `token_env` is set. A non-2xx status is an error. The body is read through `into_reader().take(max_bytes + 1)`.
3. A missing `token_env` variable is a startup `error!` and the source stays never loaded. It does not panic.
4. An `http(s)` URL without the feature panics at `declare` with "rebuild with --features remote", matching the existing panic-on-bad-config style.
5. Log the token presence only, never its value.
4. **Config keys:** `token_env` becomes active. No new keys.
5. **Tests (under `--features remote`), using a tiny `std::net::TcpListener` server in a test thread:** `http_200_loads`, `http_500_keeps_last_good`, `http_timeout_keeps_last_good`, `http_oversize_rejected`, `bearer_header_sent_when_env_set`, `no_auth_header_without_token_env`. Without the feature: `http_url_without_feature_fails_declare`.
6. **Done when:** `cargo test`, `cargo test --features remote` and `cargo test --features remote,cloudflare` are green, and `cargo build --release --features remote,cloudflare` succeeds. Also `make build-linux` with the features, if you build musl.
7. **Risks:** ring (via rustls) on the musl target needs musl-gcc, so check your build host. Startup blocks for up to `timeout_secs` per HTTP source while strfry waits, so keep `timeout_secs` small.
## Phase 5: Blacklist with remote pubkeys
1. **Goal:** the blacklist also rejects pubkeys from a named pubkey source (expiry honored), checked as a union with the static list.
2. **Files:** `src/filters/blacklist.rs`, `README.md`.
3. **Tasks:**
1. Add `pubkeys_source: Option<String>` to `BlacklistConfig`, resolved in `Deserialize` through `sources::pubkey_source`. An unknown name or a wrong format is a deserialize error, so startup fails loudly.
2. In `filter_note`, after the static `pubkeys` check: `if let Some(set) = src.get() { if set.is_active(pk, now) { reject } }`. Then the IP checks continue as before.
3. Never loaded means only the static list applies (fail open for the blacklist).
4. **Config keys:** `filters.blacklist.pubkeys_source` (unset).
5. **Tests:** `remote_pubkey_rejected`, `static_still_rejected_with_source`, `expired_remote_entry_accepted`, `never_loaded_source_falls_back_to_static`, `unknown_source_name_fails_load`, `ip_and_cidr_unchanged`.
6. **Done when:** `cargo test` is green, the golden test passes, and the P1 message tests pass.
7. **Risks:** D5 (visible versus shadow).
## Phase 6: Rate limit premium exemption
1. **Goal:** active premium pubkeys skip rate limiting and the IP-ban check on the free relay.
2. **Files:** `src/filters/ratelimit.rs`, `README.md`.
3. **Tasks:**
1. Add `exempt_source: Option<String>`, resolved at deserialize.
2. Order in `filter_note`: IP `whitelist` (unchanged), then **premium check**, then `ban.is_banned`, then the token bucket.
3. A premium note returns Accept without touching `sources` tokens or the ban streak (no `reset`), so it neither consumes nor refills the IP's budget.
4. **Config keys:** `filters.ratelimit.exempt_source` (unset).
5. **Tests:** `premium_never_rate_limited`, `premium_accepted_from_banned_ip`, `premium_does_not_reset_ip_streak`, `expired_premium_is_rate_limited`, `never_loaded_source_exempts_nobody`, plus the existing four tests unchanged.
6. **Done when:** `cargo test` is green and the golden test passes.
7. **Risks:** a premium user behind a banned shared IP can still post. That is intended. A compromised premium key is unlimited on the free relay, which is mitigated by the blacklist.
## Phase 7: Content with remote words and premium IP-ban skip
1. **Goal:** remote words are merged with the static `filters` and re-normalized on reload. Premium authors skip the IP-ban check but are still word checked.
2. **Files:** `src/filters/content.rs`, `README.md`.
3. **Tasks:**
1. Add `words_source: Option<String>` and `exempt_source: Option<String>`, resolved at deserialize.
2. Keep the static normalized list as it is. Add `remote_norm: Option<(Arc<WordList>, Vec<String>)>`. On each note, if `src.get()` is not `Arc::ptr_eq` to the cached one, rebuild with `normalize`.
3. If the author is premium, skip `ban.is_banned`. On a match, shadow-reject and **do not** `strike` (D6).
4. A non-premium author keeps today's flow exactly.
4. **Config keys:** `filters.content.words_source` (unset), `filters.content.exempt_source` (unset).
5. **Tests:** `remote_word_shadow_rejects`, `remote_homoglyph_caught`, `reload_renormalizes`, `static_words_still_apply`, `premium_skips_ip_ban`, `premium_still_word_checked`, `premium_match_does_not_strike`, plus the existing content tests and `test_content_filter_homoglyph` unchanged.
6. **Done when:** `cargo test` is green and the golden test passes.
7. **Risks:** the cost of normalizing a large word list once per reload per process. Measure with 10k words in a test. If it is slow, move normalization into the loader through a format post-processor.
## Phase 8: Premium gate (whitelist extension)
1. **Goal:** on premium relays, only active premium pubkeys (plus any static whitelist entries) can write, with an explicit policy for "list never loaded".
2. **Files:** `src/filters/whitelist.rs`, `README.md`.
3. **Tasks:**
1. Add `pubkey_sources: Vec<String>` (`#[serde(default)]`), `unavailable: Unavailable` (`reject` by default, or `accept`) and `unavailable_message: Option<String>`. Resolve the sources at deserialize. Wrap `Whitelist` in a config struct plus `Deserialize`, as blacklist does.
2. Order: static pubkeys, static IPs, then each source's `is_active`, giving Accept if any matches.
3. If no match **and** any listed source is never loaded: with `reject`, Reject with `unavailable_message` (default per D3); with `accept`, Accept and `warn!` (rate limited in the log). Otherwise Reject with `message` (P1 default).
4. **Config keys:** `filters.whitelist.pubkey_sources` (`[]`), `filters.whitelist.unavailable` (`"reject"`), `filters.whitelist.unavailable_message` (`"blocked: membership list unavailable, try again shortly"`).
5. **Tests:** `premium_pubkey_accepted`, `non_premium_rejected_with_message`, `expired_premium_rejected`, `static_pubkey_still_accepted`, `localhost_ip_still_accepted`, `never_loaded_reject_policy`, `never_loaded_accept_policy`, `loaded_from_cache_counts_as_loaded`, `no_sources_behaves_as_today`.
6. **Done when:** `cargo test` is green, the golden test passes (its whitelist has no sources), and `test_whitelist_reject` is unchanged.
7. **Risks:** D9 (stream and sync sources) and D10 (zaps and gift wraps). The pipeline order matters: put `blacklist` before `whitelist`, so a blacklisted premium user gets the blacklist message.
## Phase 9: Example configs, README, deployment checklist
1. **Goal:** two ready-to-edit configs, documentation, and a checklist an operator can follow.
2. **Files:** add `noteguard-free.example.toml`, `noteguard-premium.example.toml` and `DEPLOY.md` (or a README section). Change `README.md` and `tests/golden.rs` (or `src/main.rs` tests).
3. **Tasks:**
1. Free: `pipeline = ["protected_events", "kinds", "blacklist", "content", "ratelimit"]` (**no whitelist**). Sources `premium`, `blacklist_pubkeys`, `blacklist_words`. ratelimit and content use `exempt_source = "premium"`.
2. Premium: `pipeline = ["protected_events", "kinds", "blacklist", "whitelist", "content", "ratelimit"]`, with the whitelist `pubkey_sources = ["premium"]` and ratelimit per D4.
3. Both use `token_env = "AZZAMO_API_TOKEN"` and `cache_path = "/var/lib/noteguard/<name>.json"`.
4. Test: parse both example files and run `load_config` with the sources declared but not started (no network), and assert the pipeline lengths.
5. The checklist covers: the build command (`cargo build --release --features remote,cloudflare`); setting `AZZAMO_API_TOKEN` (and `CLOUDFLARE_API_TOKEN`) in the strfry service environment, since the plugin inherits strfry's env; creating the cache directory writable by the strfry user; `NOTEGUARD_CONFIG` per relay; the smoke test (`< test/inputs ./noteguard` with the relay config); log lines to expect (loaded N entries, M skipped); the rollback steps from above; and the rollout order free, then asia, then us, then relay.
4. **Config keys:** none new.
5. **Tests:** `free_example_config_loads`, `premium_example_config_loads`, `repo_noteguard_toml_still_loads`.
6. **Done when:** `cargo test` and `cargo test --features remote,cloudflare` are green, the README links both examples, and the checklist has been reviewed by you.
7. **Risks:** the example URLs are placeholders until D1 is answered.
## Phase 10 (optional): NIP-05 whitelist source
1. **Goal:** a source format that reads a `nostr.json` `names` map, usable through `whitelist.pubkey_sources`. Off unless configured.
2. **Files:** `src/sources/parse.rs` (`Format::Nip05`), `README.md`, example snippet.
3. **Tasks:**
1. `parse_nip05`: `{"names": {"alice": "<hex>", ...}}` gives a `PubkeySet` with no expiries. It ignores `relays` and validates hex as in P2.
2. Document `format = "nip05"` with `url = "https://example.com/.well-known/nostr.json"`.
4. **Config keys:** `format = "nip05"` becomes valid.
5. **Tests:** `nip05_names_parsed`, `nip05_invalid_hex_skipped`, `nip05_missing_names_is_error`, `whitelist_accepts_nip05_member`.
6. **Done when:** `cargo test` and `cargo test --features remote` are green.
7. **Risks:** some servers only answer `?name=` queries and do not return the full map. Document that the full map is required.
---
## Verification (every phase)
```
cargo test
cargo test --features cloudflare
cargo test --features remote # from P4 on
cargo test --features remote,cloudflare # from P4 on
cargo build --release --features remote,cloudflare
```
Plus the golden test from P0 passing unchanged, and a manual `< test/inputs ./target/debug/noteguard` with the phase's example config.
## Skipped or not checked
- I did not run `cargo test` during planning (planning was read only). P0 records the baseline.
- I did not verify strfry's plugin-reload-on-mtime behavior against your strfry version.
- I did not check the real Azzamo API response shape (D1).
- The forwarder and nscript features are not exercised by these phases.