sources: nip05 format for whitelisting a domain's NIP-05 users
Phase 10 of PLAN.md (optional, off unless configured). `format = "nip05"` reads a nostr.json `names` map into a pubkey list with no expiries, usable anywhere a pubkey source is, e.g. `whitelist.pubkey_sources`. A body without a `names` object is an error, so a server that only answers ?name= lookups is caught at load time. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
f63e2d9087
commit
059e763022
@@ -123,7 +123,7 @@ level of the config:
|
||||
```toml
|
||||
[sources.premium]
|
||||
url = "https://api.example.com/premium" # https://, http://, file:///path or a plain path
|
||||
format = "pubkeys" # "pubkeys" or "words"
|
||||
format = "pubkeys" # "pubkeys", "words" or "nip05"
|
||||
token_env = "AZZAMO_API_TOKEN" # optional: env var holding a bearer token
|
||||
reload_secs = 300 # optional: default 300, minimum 30
|
||||
timeout_secs = 10 # optional: per-request timeout, default 10
|
||||
@@ -148,6 +148,16 @@ counted in the log):
|
||||
|
||||
- `format = "pubkeys"`: a JSON array, or `{"pubkeys": [...]}`, whose items are either a hex pubkey string or `{"pubkey": "<hex>", "expires_at": <unix seconds or null>}`. Keys are lowercased; npub and malformed keys are skipped. An entry stops counting once `expires_at` passes, even if the API is down and the list is stale. A key listed twice keeps the latest expiry.
|
||||
- `format = "words"`: a JSON array of strings, or `{"words": [...]}`.
|
||||
- `format = "nip05"`: a NIP-05 `nostr.json` document; every pubkey in its `names` map is listed, with no expiry. The server must return the full map (some only answer `?name=` lookups; that body has no `names` map for everyone and is rejected). Use it with `whitelist.pubkey_sources` to let only a domain's NIP-05 users write:
|
||||
|
||||
```toml
|
||||
[sources.members]
|
||||
url = "https://example.com/.well-known/nostr.json"
|
||||
format = "nip05"
|
||||
|
||||
[filters.whitelist]
|
||||
pubkey_sources = ["members"]
|
||||
```
|
||||
|
||||
HTTP sources need a build with `--features remote`; a config with an http(s)
|
||||
source in a build without it stops at startup with an error.
|
||||
|
||||
@@ -246,6 +246,24 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whitelist_accepts_nip05_member() {
|
||||
let member = "16c21558762108afc34e4ff19e4ed51d9a48f79e0c34531efc423d21ab435e93";
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("noteguard-wl-nip05-{}", std::process::id()))
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
std::fs::write(&path, format!(r#"{{"names": {{"alice": "{member}"}}}}"#)).unwrap();
|
||||
let config: SourceConfig =
|
||||
toml::from_str(&format!("url = \"{path}\"\nformat = \"nip05\"")).unwrap();
|
||||
declare(&HashMap::from([("wl_nip05".to_string(), config)])).unwrap();
|
||||
pubkey_source("wl_nip05").unwrap().initial_load();
|
||||
|
||||
let mut w = whitelist("pubkey_sources = [\"wl_nip05\"]");
|
||||
assert_eq!(run(&mut w, member, "1.1.1.1").action, Action::Accept);
|
||||
assert_eq!(run(&mut w, "stranger", "1.1.1.1").action, Action::Reject);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_sources_behaves_as_today() {
|
||||
let mut w = whitelist("pubkeys = [\"admin\"]\nips = [\"127.0.0.1\"]");
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ mod http;
|
||||
pub mod parse;
|
||||
pub mod runtime;
|
||||
|
||||
pub use parse::{parse_pubkeys, parse_words, Format, PubkeySet, WordList};
|
||||
pub use parse::{parse_nip05, parse_pubkeys, parse_words, Format, PubkeySet, WordList};
|
||||
pub use runtime::{
|
||||
declare, now_unix, pubkey_source, start, word_source, Declared, PubkeyRef, Source,
|
||||
SourceConfig, WordsRef,
|
||||
|
||||
@@ -17,6 +17,9 @@ pub enum Format {
|
||||
Pubkeys,
|
||||
/// Words or phrases (content blocklist).
|
||||
Words,
|
||||
/// A NIP-05 `nostr.json` document: the pubkeys of its `names` map, with no
|
||||
/// expiry. Usable anywhere a pubkey list is (e.g. `whitelist`).
|
||||
Nip05,
|
||||
}
|
||||
|
||||
/// Hex pubkeys, each with an optional expiry in unix seconds (`None` never
|
||||
@@ -139,6 +142,28 @@ pub fn parse_words(body: &[u8]) -> Result<(WordList, usize), String> {
|
||||
Ok((WordList(words), skipped))
|
||||
}
|
||||
|
||||
/// Parse a NIP-05 `nostr.json` (`{"names": {"alice": "<hex>", ...}}`) into a
|
||||
/// pubkey set with no expiries. `relays` and other fields are ignored; invalid
|
||||
/// keys are skipped and counted. A body without a `names` object is an error,
|
||||
/// so a server that only answers `?name=` lookups is caught at load time.
|
||||
pub fn parse_nip05(body: &[u8]) -> Result<(PubkeySet, usize), String> {
|
||||
let value: Value = serde_json::from_slice(body).map_err(|e| format!("invalid JSON: {e}"))?;
|
||||
let names = value
|
||||
.get("names")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or("expected a NIP-05 document with a \"names\" object")?;
|
||||
|
||||
let mut set = PubkeySet::default();
|
||||
let mut skipped = 0;
|
||||
for pubkey in names.values() {
|
||||
match pubkey.as_str().and_then(normalize_hex_pubkey) {
|
||||
Some(pk) => set.insert(pk, None),
|
||||
None => skipped += 1,
|
||||
}
|
||||
}
|
||||
Ok((set, skipped))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -244,6 +269,37 @@ mod tests {
|
||||
assert_eq!(words.0, vec!["spam"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nip05_names_parsed() {
|
||||
let (set, skipped) = parse_nip05(
|
||||
format!(
|
||||
r#"{{"names": {{"alice": "{A}", "bob": "{}"}}, "relays": {{}}}}"#,
|
||||
B.to_uppercase()
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((set.len(), skipped), (2, 0));
|
||||
assert!(set.is_active(A, u64::MAX));
|
||||
assert!(set.is_active(B, u64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nip05_invalid_hex_skipped() {
|
||||
let (set, skipped) = parse_nip05(
|
||||
format!(r#"{{"names": {{"a": "{A}", "b": "npub1x", "c": 7}}}}"#).as_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((set.len(), skipped), (1, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nip05_missing_names_is_error() {
|
||||
assert!(parse_nip05(br#"{"relays": {}}"#).is_err());
|
||||
assert!(parse_nip05(br#"{"names": ["not", "a", "map"]}"#).is_err());
|
||||
assert!(parse_nip05(b"[]").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_json_is_error() {
|
||||
assert!(parse_pubkeys(b"<html>502 Bad Gateway</html>").is_err());
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
//! fetched by each process. Cache writes go through a per-process temp file
|
||||
//! and an atomic rename, so concurrent writers never leave a torn file.
|
||||
|
||||
use super::parse::{parse_pubkeys, parse_words, Format, PubkeySet, WordList};
|
||||
use super::parse::{parse_nip05, parse_pubkeys, parse_words, Format, PubkeySet, WordList};
|
||||
use log::{error, info, warn};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use std::collections::HashMap;
|
||||
@@ -144,6 +144,7 @@ impl List for PubkeySet {
|
||||
fn parse(format: Format, body: &[u8]) -> Result<(Self, usize), String> {
|
||||
match format {
|
||||
Format::Pubkeys => parse_pubkeys(body),
|
||||
Format::Nip05 => parse_nip05(body),
|
||||
Format::Words => Err("format `words` does not hold pubkeys".to_string()),
|
||||
}
|
||||
}
|
||||
@@ -157,7 +158,9 @@ impl List for WordList {
|
||||
fn parse(format: Format, body: &[u8]) -> Result<(Self, usize), String> {
|
||||
match format {
|
||||
Format::Words => parse_words(body),
|
||||
Format::Pubkeys => Err("format `pubkeys` does not hold words".to_string()),
|
||||
Format::Pubkeys | Format::Nip05 => {
|
||||
Err(format!("format `{format:?}` does not hold words"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,7 +334,7 @@ pub fn declare(configs: &HashMap<String, SourceConfig>) -> Result<Declared, Stri
|
||||
}
|
||||
}
|
||||
let entry = match config.format {
|
||||
Format::Pubkeys => {
|
||||
Format::Pubkeys | Format::Nip05 => {
|
||||
let source = Arc::new(Source::<PubkeySet>::new(name, config.clone()));
|
||||
declared.push(source.clone());
|
||||
Entry::Pubkeys(source)
|
||||
|
||||
Reference in New Issue
Block a user