nscript: experimental wasm note filter, on both the write and read paths
Add an experimental `nscript` filter that runs a user-supplied WASM guest, behind the `nscript` cargo feature (wasmtime), on both the write path (should this note be stored) and the read path (should this note be delivered to this subscriber). This is the experimental part of the plugin work — the readPolicy trait, engine and throttles in the preceding commits stand on their own without it, and a build without the feature skips an `nscript` pipeline entry (fail open) rather than failing. The ABI is an accessor interface over an opaque note handle: the guest never parses a note buffer, it calls imported `note_*` host functions (note_pubkey/id/kind/created_at/content, note_targets_owner, is_following, log) to read fields. The note's byte format is thus a host implementation detail — today backed by the serde Note; later an ndb_note with an optional zero-copy raw fast path. Owner-relative context (the scoped npub and its follows) lives on the host so guests stay reusable, owner-agnostic logic. Guests are bounded by wasm fuel and a memory cap per note, and noteguard fails open on trap/exhaustion so a broken or runaway filter can't block writes, hang the relay, or withhold a subscriber's own authorized feed. On the read path the subscriber (the NIP-42 authed pubkey) is the script owner, so a per-npub feed filter runs scoped to whoever is reading. Runtime::rescope re-binds an already-compiled guest to a different owner and follow-set by cloning the (internally reference-counted) engine/module/linker, so the guest is JIT-compiled once per process and a subscription costs no compile or file read on strfry's serving thread; a failed load is logged once rather than once per subscription. The Verdict collapses on the read path to deliver (Accept) vs withhold (anything else) — there is no shadow concept for reads. Only this filter calls UnparsedNote::parse(); the throttles still never deserialize a Note. Script/follow distribution is stubbed for this phase (configured statically via `module`/`owner`/`follows` rather than sourced from signed submission events on the relay); the point today is the ABI + runtime wiring. Includes three example guests: follows-only (an inbox filter, <300 bytes with no note parser linked in), an adversarial infinite-loop guest, and mute-word (an owner-independent content mute, convenient for exercising the read path without AUTH). Verified end-to-end on the write path: followed->accept, stranger->reject, off-target->accept, and the spinner is stopped by fuel in ~15ms. And on the read path against strfry (branch config): content filtering withholds exactly the muted events, a trapping guest fails open and delivers all; plugin logs show reqOpen(+filter) -> req(+events) -> connClose. Changelog-Added: Experimental nscript WASM note filter (behind the `nscript` feature), on both the write path and the readPolicy delivery path Headway: headway:noteguard/chair-kick-reopen Headway: headway:noteguard/gloom-lucky-budget Agentium: agentium:exhaust-bus-combine Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
a9638232a8
commit
4265d3a019
Generated
+840
-58
File diff suppressed because it is too large
Load Diff
@@ -5,6 +5,8 @@ edition = "2021"
|
||||
|
||||
[features]
|
||||
forwarder = ["tokio-tungstenite", "tokio", "futures-util"]
|
||||
# nscript: run user-submitted WASM note filters (Phase 0 spike)
|
||||
nscript = ["wasmtime"]
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
@@ -18,3 +20,6 @@ tokio = { version = "1.38.0", features = ["macros", "time", "sync", "rt-multi-th
|
||||
futures-util = { version = "0.3.30", optional = true }
|
||||
log = "0.4.22"
|
||||
env_logger = "0.11.3"
|
||||
|
||||
# nscript deps
|
||||
wasmtime = { version = "48", optional = true, default-features = false, features = ["cranelift", "runtime", "std"] }
|
||||
|
||||
@@ -166,6 +166,57 @@ be queued if the connection goes down (up to the `queue_size` buffer limit)
|
||||
|
||||
- `queue_size` *optional* - size of the note queue, this is used to buffer notes if the connection goes down. Default is 1000.
|
||||
|
||||
### NScript (experimental)
|
||||
|
||||
* name: `nscript`
|
||||
|
||||
Runs a user-supplied **WASM** module as a note filter. Instead of compiling
|
||||
filters into noteguard, the logic lives in a sandboxed wasm guest that reads the
|
||||
note through an *accessor ABI* — a set of imported host functions
|
||||
(`note_pubkey`, `note_kind`, `note_targets_owner`, `is_following`, …) — rather
|
||||
than parsing a note buffer itself. The note's byte format is therefore an
|
||||
implementation detail of the host, and guests stay tiny (the example below is
|
||||
under 300 bytes: no note parser is linked into it).
|
||||
|
||||
The intent is programmable, per-npub server-side filtering (e.g. inbox / mention
|
||||
spam control), eventually submitted to the relay as a signed event. This is a
|
||||
**Phase 0 spike**: the guest is loaded from a local path and the owner context
|
||||
comes from config.
|
||||
|
||||
Build with the `nscript` feature:
|
||||
|
||||
```sh
|
||||
$ cargo build --features nscript
|
||||
```
|
||||
|
||||
Config:
|
||||
|
||||
- `module` — path to the compiled guest `.wasm`
|
||||
- `owner` *optional* — hex pubkey the script is scoped to (its "inbox owner")
|
||||
- `follows` *optional* — hex pubkeys the owner follows (backs `is_following`)
|
||||
- `message` *optional* — message returned to the client on reject
|
||||
|
||||
```toml
|
||||
[filters.nscript]
|
||||
module = "./follows_only.wasm"
|
||||
owner = "1111…1111"
|
||||
follows = ["2222…2222"]
|
||||
message = "blocked: not in owner's follows"
|
||||
```
|
||||
|
||||
Guests are bounded by wasm **fuel** and a **memory cap** per note, and noteguard
|
||||
**fails open** (accepts) if a guest traps or exhausts its budget, so a broken or
|
||||
runaway filter can't block writes or hang the relay.
|
||||
|
||||
An example guest (`follows-only`, an inbox filter that rejects notes to the owner
|
||||
from non-followed authors) lives in [`nscript-guests/`](nscript-guests). Build it
|
||||
with:
|
||||
|
||||
```sh
|
||||
$ cd nscript-guests/follows-only
|
||||
$ cargo build --release --target wasm32-unknown-unknown
|
||||
```
|
||||
|
||||
## Read-policy (readPolicy) mode
|
||||
|
||||
Everything above is the **write-side** plugin: it decides what gets *stored* (a
|
||||
@@ -201,7 +252,7 @@ subscription is passthrough). Filters run in order per event.
|
||||
```toml
|
||||
[readpolicy]
|
||||
# compose the read filters, in order. Empty/absent => deliver all.
|
||||
pipeline = ["max_events_per_conn", "read_bandwidth"]
|
||||
pipeline = ["max_events_per_conn", "read_bandwidth", "nscript"]
|
||||
|
||||
# connection-level throttle: max events delivered per connection.
|
||||
[readpolicy.filters.max_events_per_conn]
|
||||
@@ -219,6 +270,17 @@ bytes_per_minute = 5000000
|
||||
# hex (optional). A whitelisted connection is never metered and takes the
|
||||
# passthrough fast path.
|
||||
whitelist = ["127.0.0.1", "0000…0000"]
|
||||
|
||||
# guest wasm applied to subscriptions (owner = the authed subscriber). Requires
|
||||
# the `nscript` build feature; the pipeline entry is skipped (fail open) in a
|
||||
# build without it.
|
||||
[readpolicy.filters.nscript]
|
||||
module = "./mute_word.wasm"
|
||||
# STUB for follow-set distribution: owner-hex -> hex pubkeys they follow.
|
||||
# Backs the guest's is_following accessor until scripts/follows are sourced
|
||||
# from signed on-relay submissions.
|
||||
[readpolicy.filters.nscript.follows]
|
||||
# "1111…1111" = ["2222…2222"]
|
||||
```
|
||||
|
||||
Each filter is a [`ReadFilter`](src/read_filter.rs) — a lifecycle-aware,
|
||||
@@ -238,7 +300,8 @@ zero-copy fast path, never sending `req` batches (it still sends
|
||||
subscription, and the engine ANDs those: an empty pipeline is always
|
||||
passthrough; a configured throttle keeps the subscription non-passthrough
|
||||
(strfry must keep sending events for the counter/byte-meter to bound delivery);
|
||||
and a bandwidth-whitelisted connection is passthrough (it is never metered).
|
||||
a bandwidth-whitelisted connection is passthrough (it is never metered); and a
|
||||
`nscript` filter is non-passthrough only when it actually loaded a guest.
|
||||
Emitting the field is forward-compatible: a strfry without passthrough support
|
||||
simply ignores it.
|
||||
|
||||
@@ -261,6 +324,39 @@ For exact per-IP enforcement, set `relay.numThreads.reqWorker = 1` and
|
||||
(True cross-thread enforcement would require sharing bucket state across plugin
|
||||
processes, which this phase does not do.)
|
||||
|
||||
### NScript read filter (experimental)
|
||||
|
||||
* name: `nscript`
|
||||
|
||||
The read path can drive the same nscript WASM runtime as the write-side
|
||||
[`nscript`](#nscript-experimental) filter, so it needs the `nscript` feature
|
||||
(`cargo build --release --features nscript`); without it the pipeline entry is
|
||||
logged and skipped (fail open). The subscriber (the NIP-42 `authed` pubkey) is
|
||||
the script **owner**, so a per-npub feed filter runs scoped to whoever is
|
||||
reading. The guest is compiled once per process and re-scoped per subscriber —
|
||||
no recompile per subscription. The `Verdict` collapses on the read path to
|
||||
**deliver** (`Accept`) vs **withhold** (anything else); there is no "shadow"
|
||||
concept for reads. It fails open: a missing/failed module or a trapping guest
|
||||
delivers everything.
|
||||
|
||||
An unauthenticated subscription (no `authed`) still runs the guest, but with no
|
||||
owner: an owner-scoped filter like `follows-only` then no-ops and delivers
|
||||
everything, while an owner-independent filter still applies. The
|
||||
[`mute-word`](nscript-guests/mute-word) example guest (withholds kind-1 notes
|
||||
containing a muted word) is owner-independent, which makes it convenient for
|
||||
exercising the read path without AUTH:
|
||||
|
||||
```sh
|
||||
$ cd nscript-guests/mute-word
|
||||
$ cargo build --release --target wasm32-unknown-unknown
|
||||
```
|
||||
|
||||
Script/follow **distribution is stubbed** for this phase (configured statically
|
||||
via `module` and the `follows` map rather than sourced from signed submission
|
||||
events on the relay); the point of the read mode today is the protocol + runtime
|
||||
wiring.
|
||||
|
||||
|
||||
## Testing
|
||||
|
||||
You can test your filters like so:
|
||||
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "follows-only"
|
||||
version = "0.1.0"
|
||||
@@ -0,0 +1,16 @@
|
||||
# Standalone crate (its own workspace) so it is not pulled into noteguard's build.
|
||||
[workspace]
|
||||
|
||||
[package]
|
||||
name = "follows-only"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
panic = "abort"
|
||||
strip = true
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Example nscript guest: a follows-only inbox filter.
|
||||
//!
|
||||
//! Rejects notes addressed (p-tagged) to the scoped owner unless the author is
|
||||
//! someone the owner follows. Notes that don't target the owner are accepted
|
||||
//! untouched.
|
||||
//!
|
||||
//! Note how there is no note parser compiled into this module: it reads the note
|
||||
//! purely through the host accessor ABI. Owner-relative context (who the owner
|
||||
//! is, and their follow set) lives on the host, so this module is reusable logic
|
||||
//! independent of any particular npub.
|
||||
|
||||
#![no_std]
|
||||
|
||||
use core::panic::PanicInfo;
|
||||
|
||||
// ---- accessor ABI (imported from the host) ----
|
||||
#[link(wasm_import_module = "env")]
|
||||
extern "C" {
|
||||
/// Writes the 32-byte author pubkey into `out_ptr`; returns bytes written.
|
||||
fn note_pubkey(out_ptr: *mut u8) -> i32;
|
||||
/// 1 if the note p-tags the scoped owner, else 0.
|
||||
fn note_targets_owner() -> i32;
|
||||
/// 1 if the 32-byte pubkey at `pk_ptr` is in the owner's follow set.
|
||||
fn is_following(pk_ptr: *const u8) -> i32;
|
||||
}
|
||||
|
||||
const ACCEPT: i32 = 0;
|
||||
const REJECT: i32 = 1;
|
||||
|
||||
/// The host calls this once per note; the current note is implicit.
|
||||
#[no_mangle]
|
||||
pub extern "C" fn filter_note() -> i32 {
|
||||
unsafe {
|
||||
// Only govern notes addressed to our owner; leave everything else alone.
|
||||
if note_targets_owner() == 0 {
|
||||
return ACCEPT;
|
||||
}
|
||||
|
||||
let mut author = [0u8; 32];
|
||||
note_pubkey(author.as_mut_ptr());
|
||||
|
||||
if is_following(author.as_ptr()) == 1 {
|
||||
ACCEPT
|
||||
} else {
|
||||
REJECT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[panic_handler]
|
||||
fn panic(_: &PanicInfo) -> ! {
|
||||
loop {}
|
||||
}
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "loop-forever"
|
||||
version = "0.1.0"
|
||||
@@ -0,0 +1,14 @@
|
||||
[workspace]
|
||||
|
||||
[package]
|
||||
name = "loop-forever"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
panic = "abort"
|
||||
strip = true
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Adversarial nscript guest: never returns. Must be stopped by host fuel.
|
||||
#![no_std]
|
||||
use core::panic::PanicInfo;
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn filter_note() -> i32 {
|
||||
let mut x: u64 = 0;
|
||||
loop {
|
||||
// volatile-ish spin so the optimizer can't fold it away
|
||||
x = x.wrapping_add(1);
|
||||
unsafe { core::ptr::read_volatile(&x); }
|
||||
}
|
||||
}
|
||||
|
||||
#[panic_handler]
|
||||
fn panic(_: &PanicInfo) -> ! { loop {} }
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "mute-word"
|
||||
version = "0.1.0"
|
||||
@@ -0,0 +1,16 @@
|
||||
# Standalone crate (its own workspace) so it is not pulled into noteguard's build.
|
||||
[workspace]
|
||||
|
||||
[package]
|
||||
name = "mute-word"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[profile.release]
|
||||
opt-level = "s"
|
||||
lto = true
|
||||
panic = "abort"
|
||||
strip = true
|
||||
@@ -0,0 +1,78 @@
|
||||
//! Example nscript guest: an owner-independent muted-word read filter.
|
||||
//!
|
||||
//! Withholds kind-1 notes whose content contains the muted word "spam";
|
||||
//! everything else is delivered. Unlike `follows-only`, this guest reads no
|
||||
//! owner context, so it applies identically to every subscriber (authenticated
|
||||
//! or not) — which makes it convenient for exercising the read-side
|
||||
//! deliver/withhold path without NIP-42 AUTH.
|
||||
//!
|
||||
//! As with the other guests, there is no note parser compiled in: the content
|
||||
//! is read through the host accessor ABI.
|
||||
|
||||
#![no_std]
|
||||
|
||||
use core::panic::PanicInfo;
|
||||
|
||||
#[link(wasm_import_module = "env")]
|
||||
extern "C" {
|
||||
/// The note's kind.
|
||||
fn note_kind() -> i64;
|
||||
/// Copies up to `cap` bytes of the note content into `out_ptr`; returns the
|
||||
/// content's true length (which may exceed `cap`).
|
||||
fn note_content(out_ptr: *mut u8, cap: i32) -> i32;
|
||||
}
|
||||
|
||||
const ACCEPT: i32 = 0;
|
||||
const REJECT: i32 = 1;
|
||||
|
||||
/// The muted word. A note delivering it is withheld.
|
||||
const MUTED: &[u8] = b"spam";
|
||||
|
||||
/// Scratch buffer for the note content. Content longer than this is truncated
|
||||
/// for the scan (a muted word past the cutoff won't match — acceptable for a
|
||||
/// spike; a real filter would stream or raise the cap).
|
||||
const CAP: usize = 4096;
|
||||
|
||||
#[no_mangle]
|
||||
pub extern "C" fn filter_note() -> i32 {
|
||||
unsafe {
|
||||
// Only govern kind-1 (text notes); leave everything else alone.
|
||||
if note_kind() != 1 {
|
||||
return ACCEPT;
|
||||
}
|
||||
|
||||
let mut buf = [0u8; CAP];
|
||||
let true_len = note_content(buf.as_mut_ptr(), CAP as i32);
|
||||
let n = if true_len < 0 {
|
||||
0
|
||||
} else {
|
||||
(true_len as usize).min(CAP)
|
||||
};
|
||||
|
||||
if contains(&buf[..n], MUTED) {
|
||||
REJECT
|
||||
} else {
|
||||
ACCEPT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Naive substring search (no_std, no allocator).
|
||||
fn contains(haystack: &[u8], needle: &[u8]) -> bool {
|
||||
if needle.is_empty() || needle.len() > haystack.len() {
|
||||
return needle.is_empty();
|
||||
}
|
||||
let mut i = 0;
|
||||
while i + needle.len() <= haystack.len() {
|
||||
if &haystack[i..i + needle.len()] == needle {
|
||||
return true;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[panic_handler]
|
||||
fn panic(_: &PanicInfo) -> ! {
|
||||
loop {}
|
||||
}
|
||||
@@ -8,6 +8,9 @@ mod whitelist;
|
||||
#[cfg(feature = "forwarder")]
|
||||
mod forwarder;
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
mod nscript;
|
||||
|
||||
pub use blacklist::Blacklist;
|
||||
pub use content::Content;
|
||||
pub use kinds::Kinds;
|
||||
@@ -17,3 +20,6 @@ pub use whitelist::Whitelist;
|
||||
|
||||
#[cfg(feature = "forwarder")]
|
||||
pub use forwarder::Forwarder;
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
pub use nscript::NScript;
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
use crate::nscript::{Runtime, Verdict};
|
||||
use crate::{Action, InputMessage, NoteFilter, OutputMessage};
|
||||
use serde::Deserialize;
|
||||
|
||||
/// Runs a user-supplied WASM guest as a note filter via the accessor ABI.
|
||||
///
|
||||
/// For the Phase 0 spike the guest is loaded from a local path and the owner
|
||||
/// context comes from config; a later phase sources both from a signed
|
||||
/// submission event on the relay.
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct NScript {
|
||||
/// Path to the compiled guest `.wasm`.
|
||||
module: String,
|
||||
|
||||
/// Hex pubkey the script is scoped to (its "inbox owner").
|
||||
#[serde(default)]
|
||||
owner: Option<String>,
|
||||
|
||||
/// Hex pubkeys the owner follows (backs `is_following`).
|
||||
#[serde(default)]
|
||||
follows: Vec<String>,
|
||||
|
||||
/// Message returned to the client on reject.
|
||||
#[serde(default)]
|
||||
message: Option<String>,
|
||||
|
||||
/// Compiled runtime, built lazily on first note.
|
||||
#[serde(skip)]
|
||||
runtime: Option<Runtime>,
|
||||
}
|
||||
|
||||
impl NoteFilter for NScript {
|
||||
fn name(&self) -> &'static str {
|
||||
"nscript"
|
||||
}
|
||||
|
||||
fn filter_note(&mut self, msg: &InputMessage) -> OutputMessage {
|
||||
let id = msg.event.id.clone();
|
||||
|
||||
if self.runtime.is_none() {
|
||||
match Runtime::load(&self.module, &self.owner, &self.follows) {
|
||||
Ok(rt) => self.runtime = Some(rt),
|
||||
Err(e) => {
|
||||
// Fail open: a broken filter shouldn't block all writes.
|
||||
log::error!("nscript: failed to load {}: {}", self.module, e);
|
||||
return OutputMessage::new(id, Action::Accept, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let rt = self.runtime.as_ref().expect("runtime just loaded");
|
||||
match rt.run(&msg.event) {
|
||||
Ok(Verdict::Accept) => OutputMessage::new(id, Action::Accept, None),
|
||||
Ok(Verdict::Reject) => OutputMessage::new(id, Action::Reject, self.message.clone()),
|
||||
Ok(Verdict::ShadowReject) => OutputMessage::new(id, Action::ShadowReject, None),
|
||||
Err(e) => {
|
||||
// Fail open on guest trap / resource exhaustion.
|
||||
log::error!("nscript: guest error: {}", e);
|
||||
OutputMessage::new(id, Action::Accept, None)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,9 @@ pub mod readfilters;
|
||||
pub mod readmsg;
|
||||
pub mod readpolicy;
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
pub mod nscript;
|
||||
|
||||
pub use messages::{Action, InputMessage, OutputMessage};
|
||||
pub use note_filter::{Note, NoteFilter};
|
||||
pub use read_filter::{Admission, ConnContext, EventVerdict, OpenDecision, ReadFilter};
|
||||
|
||||
@@ -3,6 +3,9 @@ use noteguard::filters::{Blacklist, Content, Kinds, ProtectedEvents, RateLimit,
|
||||
#[cfg(feature = "forwarder")]
|
||||
use noteguard::filters::Forwarder;
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
use noteguard::filters::NScript;
|
||||
|
||||
use log::info;
|
||||
use noteguard::{Action, InputMessage, NoteFilter, OutputMessage};
|
||||
use serde::de::DeserializeOwned;
|
||||
@@ -54,6 +57,9 @@ impl Noteguard {
|
||||
|
||||
#[cfg(feature = "forwarder")]
|
||||
self.register_filter::<Forwarder>();
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
self.register_filter::<NScript>();
|
||||
}
|
||||
|
||||
/// Run the loaded filters. You must call `load_config` before calling this, otherwise
|
||||
|
||||
+290
@@ -0,0 +1,290 @@
|
||||
//! Phase 0 spike of the nscript wasm filter runtime.
|
||||
//!
|
||||
//! The ABI is an *accessor interface* over an opaque note handle: the guest
|
||||
//! never parses a note buffer, it calls imported `note_*` host functions to read
|
||||
//! fields. The note's byte format is therefore an implementation detail — today
|
||||
//! we back the accessors with the serde [`Note`]; later this becomes an
|
||||
//! `ndb_note` (with an optional `note_raw` zero-copy fast path). Owner-relative
|
||||
//! context (which npub the script is scoped to, and their follows) lives on the
|
||||
//! host, so guests stay reusable, owner-agnostic logic.
|
||||
|
||||
use crate::Note;
|
||||
use std::collections::HashSet;
|
||||
use wasmtime::{
|
||||
AsContext, AsContextMut, Caller, Config, Engine, Extern, Linker, Memory, Module, Store,
|
||||
StoreLimits, StoreLimitsBuilder,
|
||||
};
|
||||
|
||||
/// Guest action codes returned from `filter_note`.
|
||||
const ACT_REJECT: i32 = 1;
|
||||
const ACT_SHADOW_REJECT: i32 = 2;
|
||||
|
||||
/// CPU budget (wasm fuel units) per note. Bounds runaway guests deterministically.
|
||||
const DEFAULT_FUEL: u64 = 50_000_000;
|
||||
|
||||
/// Max guest linear memory (bytes).
|
||||
const MAX_MEMORY: usize = 16 * 1024 * 1024;
|
||||
|
||||
/// The verdict a guest returns for a note.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Verdict {
|
||||
Accept,
|
||||
Reject,
|
||||
ShadowReject,
|
||||
}
|
||||
|
||||
/// Per-invocation host state exposed to the accessor functions.
|
||||
struct HostState {
|
||||
note: Note,
|
||||
owner: Option<[u8; 32]>,
|
||||
follows: HashSet<[u8; 32]>,
|
||||
limits: StoreLimits,
|
||||
}
|
||||
|
||||
/// A compiled nscript module plus the owner context it runs under.
|
||||
pub struct Runtime {
|
||||
engine: Engine,
|
||||
module: Module,
|
||||
linker: Linker<HostState>,
|
||||
owner: Option<[u8; 32]>,
|
||||
follows: HashSet<[u8; 32]>,
|
||||
fuel: u64,
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
/// Compile the guest at `path` and wire up the accessor ABI.
|
||||
///
|
||||
/// `owner` is the hex pubkey the script is scoped to and `follows` are hex
|
||||
/// pubkeys that owner follows (backing for `note_targets_owner` and
|
||||
/// `is_following`).
|
||||
pub fn load(path: &str, owner: &Option<String>, follows: &[String]) -> Result<Self, String> {
|
||||
let mut config = Config::new();
|
||||
config.consume_fuel(true);
|
||||
let engine = Engine::new(&config).map_err(|e| e.to_string())?;
|
||||
let module = Module::from_file(&engine, path).map_err(|e| e.to_string())?;
|
||||
|
||||
let mut linker = Linker::new(&engine);
|
||||
register_host_functions(&mut linker).map_err(|e| e.to_string())?;
|
||||
|
||||
let owner = owner.as_deref().and_then(hex32);
|
||||
let follows = follows.iter().filter_map(|h| hex32(h)).collect();
|
||||
|
||||
Ok(Runtime {
|
||||
engine,
|
||||
module,
|
||||
linker,
|
||||
owner,
|
||||
follows,
|
||||
fuel: DEFAULT_FUEL,
|
||||
})
|
||||
}
|
||||
|
||||
/// Re-scope this already-compiled guest to a different owner, without
|
||||
/// recompiling. `engine`, `module` and `linker` are owner-independent and
|
||||
/// internally reference-counted, so cloning them is cheap — a per-subscriber
|
||||
/// runtime costs no JIT compile or file read.
|
||||
pub fn rescope(&self, owner: &Option<String>, follows: &[String]) -> Self {
|
||||
Runtime {
|
||||
engine: self.engine.clone(),
|
||||
module: self.module.clone(),
|
||||
linker: self.linker.clone(),
|
||||
owner: owner.as_deref().and_then(hex32),
|
||||
follows: follows.iter().filter_map(|h| hex32(h)).collect(),
|
||||
fuel: self.fuel,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the guest filter against `note`, returning its verdict.
|
||||
///
|
||||
/// A fresh [`Store`] is created per note (the compiled module is reused), so
|
||||
/// guests get no state between invocations. Fuel and a memory cap bound the
|
||||
/// resources a single call may consume.
|
||||
pub fn run(&self, note: &Note) -> Result<Verdict, String> {
|
||||
let state = HostState {
|
||||
note: note.clone(),
|
||||
owner: self.owner,
|
||||
follows: self.follows.clone(),
|
||||
limits: StoreLimitsBuilder::new().memory_size(MAX_MEMORY).build(),
|
||||
};
|
||||
let mut store = Store::new(&self.engine, state);
|
||||
store.limiter(|s| &mut s.limits);
|
||||
store.set_fuel(self.fuel).map_err(|e| e.to_string())?;
|
||||
|
||||
let instance = self
|
||||
.linker
|
||||
.instantiate(&mut store, &self.module)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let func = instance
|
||||
.get_typed_func::<(), i32>(&mut store, "filter_note")
|
||||
.map_err(|e| e.to_string())?;
|
||||
let code = func.call(&mut store, ()).map_err(|e| e.to_string())?;
|
||||
|
||||
Ok(match code {
|
||||
ACT_REJECT => Verdict::Reject,
|
||||
ACT_SHADOW_REJECT => Verdict::ShadowReject,
|
||||
_ => Verdict::Accept,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Register the accessor ABI on the linker under the `env` module.
|
||||
///
|
||||
/// Low-level accessors (`note_pubkey`, `note_id`, `note_kind`, `note_created_at`,
|
||||
/// `note_content`) expose raw note fields; higher-level owner-relative
|
||||
/// capabilities (`note_targets_owner`, `is_following`) keep owner context on the
|
||||
/// host. Variable-length reads use the `(out_ptr, cap) -> true_len` convention.
|
||||
fn register_host_functions(linker: &mut Linker<HostState>) -> Result<(), wasmtime::Error> {
|
||||
// note_pubkey(out_ptr) -> 32 : raw author pubkey bytes (0 on error)
|
||||
linker.func_wrap(
|
||||
"env",
|
||||
"note_pubkey",
|
||||
|mut caller: Caller<'_, HostState>, out: i32| -> i32 {
|
||||
let pk = match hex32(&caller.data().note.pubkey) {
|
||||
Some(p) => p,
|
||||
None => return 0,
|
||||
};
|
||||
write_bytes(&mut caller, out, &pk)
|
||||
},
|
||||
)?;
|
||||
|
||||
// note_id(out_ptr) -> 32 : raw event id bytes (0 on error)
|
||||
linker.func_wrap(
|
||||
"env",
|
||||
"note_id",
|
||||
|mut caller: Caller<'_, HostState>, out: i32| -> i32 {
|
||||
let id = match hex32(&caller.data().note.id) {
|
||||
Some(p) => p,
|
||||
None => return 0,
|
||||
};
|
||||
write_bytes(&mut caller, out, &id)
|
||||
},
|
||||
)?;
|
||||
|
||||
// note_kind() -> kind
|
||||
linker.func_wrap("env", "note_kind", |caller: Caller<'_, HostState>| -> i64 {
|
||||
caller.data().note.kind
|
||||
})?;
|
||||
|
||||
// note_created_at() -> unix seconds
|
||||
linker.func_wrap(
|
||||
"env",
|
||||
"note_created_at",
|
||||
|caller: Caller<'_, HostState>| -> i64 { caller.data().note.created_at },
|
||||
)?;
|
||||
|
||||
// note_content(out_ptr, cap) -> true_len : utf8 content, truncated to cap
|
||||
linker.func_wrap(
|
||||
"env",
|
||||
"note_content",
|
||||
|mut caller: Caller<'_, HostState>, out: i32, cap: i32| -> i32 {
|
||||
let content = caller.data().note.content.clone();
|
||||
let bytes = content.as_bytes();
|
||||
let n = bytes.len().min(cap.max(0) as usize);
|
||||
write_bytes(&mut caller, out, &bytes[..n]);
|
||||
bytes.len() as i32
|
||||
},
|
||||
)?;
|
||||
|
||||
// note_targets_owner() -> bool : does the note p-tag the scoped owner?
|
||||
linker.func_wrap(
|
||||
"env",
|
||||
"note_targets_owner",
|
||||
|caller: Caller<'_, HostState>| -> i32 {
|
||||
let owner = match caller.data().owner {
|
||||
Some(o) => o,
|
||||
None => return 0,
|
||||
};
|
||||
let hit =
|
||||
caller.data().note.tags.iter().any(|t| {
|
||||
t.len() >= 2 && t[0] == "p" && hex32(&t[1]).map_or(false, |p| p == owner)
|
||||
});
|
||||
hit as i32
|
||||
},
|
||||
)?;
|
||||
|
||||
// is_following(pk_ptr) -> bool : is this 32-byte pubkey in the owner's follows?
|
||||
linker.func_wrap(
|
||||
"env",
|
||||
"is_following",
|
||||
|mut caller: Caller<'_, HostState>, pk_ptr: i32| -> i32 {
|
||||
let target = match read_array::<32>(&mut caller, pk_ptr) {
|
||||
Some(b) => b,
|
||||
None => return 0,
|
||||
};
|
||||
caller.data().follows.contains(&target) as i32
|
||||
},
|
||||
)?;
|
||||
|
||||
// log(ptr, len) : debug logging from the guest
|
||||
linker.func_wrap(
|
||||
"env",
|
||||
"log",
|
||||
|mut caller: Caller<'_, HostState>, ptr: i32, len: i32| {
|
||||
if let Some(s) = read_str(&mut caller, ptr, len) {
|
||||
log::info!("nscript: {}", s);
|
||||
}
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolve the guest's exported linear memory.
|
||||
fn memory(caller: &mut Caller<'_, HostState>) -> Option<Memory> {
|
||||
match caller.get_export("memory") {
|
||||
Some(Extern::Memory(m)) => Some(m),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Write `data` into guest memory at `ptr`, returning the number of bytes
|
||||
/// written (0 on failure).
|
||||
fn write_bytes(caller: &mut Caller<'_, HostState>, ptr: i32, data: &[u8]) -> i32 {
|
||||
let mem = match memory(caller) {
|
||||
Some(m) => m,
|
||||
None => return 0,
|
||||
};
|
||||
match mem.write(caller.as_context_mut(), ptr as usize, data) {
|
||||
Ok(()) => data.len() as i32,
|
||||
Err(_) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a fixed-size array from guest memory at `ptr`.
|
||||
fn read_array<const N: usize>(caller: &mut Caller<'_, HostState>, ptr: i32) -> Option<[u8; N]> {
|
||||
let mem = memory(caller)?;
|
||||
let mut buf = [0u8; N];
|
||||
mem.read(caller.as_context(), ptr as usize, &mut buf).ok()?;
|
||||
Some(buf)
|
||||
}
|
||||
|
||||
/// Read a utf8 string of `len` bytes from guest memory at `ptr`.
|
||||
fn read_str(caller: &mut Caller<'_, HostState>, ptr: i32, len: i32) -> Option<String> {
|
||||
let mem = memory(caller)?;
|
||||
let mut buf = vec![0u8; len.max(0) as usize];
|
||||
mem.read(caller.as_context(), ptr as usize, &mut buf).ok()?;
|
||||
String::from_utf8(buf).ok()
|
||||
}
|
||||
|
||||
/// Decode a single hex nibble.
|
||||
fn hex_val(c: u8) -> Option<u8> {
|
||||
match c {
|
||||
b'0'..=b'9' => Some(c - b'0'),
|
||||
b'a'..=b'f' => Some(c - b'a' + 10),
|
||||
b'A'..=b'F' => Some(c - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode a 64-char hex string into a 32-byte array.
|
||||
fn hex32(s: &str) -> Option<[u8; 32]> {
|
||||
let b = s.as_bytes();
|
||||
if b.len() != 64 {
|
||||
return None;
|
||||
}
|
||||
let mut out = [0u8; 32];
|
||||
for (i, byte) in out.iter_mut().enumerate() {
|
||||
*byte = (hex_val(b[2 * i])? << 4) | hex_val(b[2 * i + 1])?;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
+2
-2
@@ -86,8 +86,8 @@ pub enum Admission {
|
||||
/// The engine ANDs `!needs_events` across all filters to decide passthrough: a
|
||||
/// subscription is passthrough (strfry skips per-event marshaling) only if *no*
|
||||
/// filter needs per-event work. `needs_events` is evaluated per subscription, so
|
||||
/// it may depend on per-sub state established in `req_open` (e.g. whether this
|
||||
/// connection is bandwidth-whitelisted).
|
||||
/// it may depend on per-sub state established in `req_open` (e.g. whether a guest
|
||||
/// actually loaded, or whether this connection is bandwidth-whitelisted).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct OpenDecision {
|
||||
pub admission: Admission,
|
||||
|
||||
@@ -5,5 +5,11 @@
|
||||
mod bandwidth;
|
||||
mod max_events;
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
mod nscript;
|
||||
|
||||
pub use bandwidth::ReadBandwidth;
|
||||
pub use max_events::MaxEventsPerConn;
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
pub use nscript::NScriptRead;
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
use crate::nscript::{Runtime, Verdict};
|
||||
use crate::read_filter::{ConnContext, EventVerdict, OpenDecision, ReadFilter};
|
||||
use crate::readmsg::UnparsedNote;
|
||||
use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Runs a user-supplied WASM guest as a per-subscription deliverability filter,
|
||||
/// scoped to the subscriber (the NIP-42 `authed` pubkey = the script owner).
|
||||
///
|
||||
/// The guest is compiled once per process and re-scoped (no recompile) to each
|
||||
/// subscriber at `req_open`. The [`Verdict`] collapses on the read path to
|
||||
/// deliver (`Accept`) vs withhold (anything else) — there is no shadow concept
|
||||
/// for reads. Fails open: a missing/failed module or a trapping guest delivers.
|
||||
///
|
||||
/// The `module` + `follows` fields stub out the eventual script-distribution
|
||||
/// system: today the guest and its owner's follow-set are configured statically;
|
||||
/// later they come from a signed submission event on the relay.
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct NScriptRead {
|
||||
/// Path to the compiled guest `.wasm`, applied to every subscription (owner =
|
||||
/// the authed subscriber). If unset, deliver everything.
|
||||
pub module: Option<String>,
|
||||
|
||||
/// STUB for follow-set distribution: owner-hex -> the hex pubkeys that owner
|
||||
/// follows (backs the guest's `is_following` accessor).
|
||||
#[serde(default)]
|
||||
pub follows: HashMap<String, Vec<String>>,
|
||||
|
||||
/// The compiled guest, built once on the first `req_open` and re-scoped per
|
||||
/// subscriber. Stays `None` when no module is configured or the load failed
|
||||
/// (fail open — deliver all); `load_attempted` keeps us from retrying a
|
||||
/// broken module (and re-logging) on every subscription.
|
||||
#[serde(skip)]
|
||||
compiled: Option<Runtime>,
|
||||
#[serde(skip)]
|
||||
load_attempted: bool,
|
||||
|
||||
/// `connId` -> `subId` -> that subscriber's scoped guest. Only subscriptions
|
||||
/// that actually have a guest get an entry; everything else delivers all.
|
||||
#[serde(skip)]
|
||||
runtimes: HashMap<u64, HashMap<String, Runtime>>,
|
||||
}
|
||||
|
||||
impl NScriptRead {
|
||||
/// The compiled guest, compiling it on first use. Returns `None` — meaning
|
||||
/// deliver-all — when no module is configured or the load failed (fail
|
||||
/// open); the failure is logged once, not once per subscription.
|
||||
fn compiled(&mut self) -> Option<&Runtime> {
|
||||
if !self.load_attempted {
|
||||
self.load_attempted = true;
|
||||
if let Some(module) = &self.module {
|
||||
// Compiled owner-less; `rescope` binds each subscriber's owner
|
||||
// and follow-set without recompiling.
|
||||
match Runtime::load(module, &None, &[]) {
|
||||
Ok(rt) => self.compiled = Some(rt),
|
||||
Err(e) => log::error!(
|
||||
"readpolicy: failed to load {} (delivering all): {}",
|
||||
module,
|
||||
e
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
self.compiled.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl ReadFilter for NScriptRead {
|
||||
fn name(&self) -> &'static str {
|
||||
"nscript"
|
||||
}
|
||||
|
||||
/// An unauthenticated subscription (`authed` == `None`) still runs the
|
||||
/// guest, but with no owner: an owner-scoped filter (like `follows-only`)
|
||||
/// then no-ops and delivers everything, while an owner-independent filter
|
||||
/// (e.g. content muting) still applies.
|
||||
fn req_open(&mut self, ctx: &ConnContext, _filter: Option<&serde_json::Value>) -> OpenDecision {
|
||||
let owner = ctx.authed.map(str::to_string);
|
||||
let follows = ctx
|
||||
.authed
|
||||
.and_then(|owner| self.follows.get(owner))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
// Only a subscription that actually has a guest does per-event work; a
|
||||
// deliver-all sub (no module / failed load) can take passthrough.
|
||||
let Some(runtime) = self.compiled().map(|rt| rt.rescope(&owner, &follows)) else {
|
||||
return OpenDecision::passthrough();
|
||||
};
|
||||
|
||||
self.runtimes
|
||||
.entry(ctx.conn_id)
|
||||
.or_default()
|
||||
.insert(ctx.sub_id.to_string(), runtime);
|
||||
OpenDecision::needs_events()
|
||||
}
|
||||
|
||||
fn filter_event(&mut self, ctx: &ConnContext, ev: &UnparsedNote) -> EventVerdict {
|
||||
// No runtime (no module / failed load / never opened): deliver.
|
||||
let Some(rt) = self
|
||||
.runtimes
|
||||
.get(&ctx.conn_id)
|
||||
.and_then(|subs| subs.get(ctx.sub_id))
|
||||
else {
|
||||
return EventVerdict::Deliver;
|
||||
};
|
||||
|
||||
// Only the guest path pays for a full parse.
|
||||
let note = match ev.parse() {
|
||||
Ok(note) => note,
|
||||
// Fail open on a malformed event, matching strfry's stance.
|
||||
Err(e) => {
|
||||
log::error!("readpolicy: unparseable event (delivering): {}", e);
|
||||
return EventVerdict::Deliver;
|
||||
}
|
||||
};
|
||||
|
||||
match rt.run(¬e) {
|
||||
Ok(Verdict::Accept) => EventVerdict::Deliver,
|
||||
// Reject / ShadowReject both collapse to withhold-this-event on the
|
||||
// read path — there is no shadow concept for deliverability.
|
||||
Ok(_) => EventVerdict::Skip,
|
||||
Err(e) => {
|
||||
// Fail open on guest trap / resource exhaustion.
|
||||
log::error!("readpolicy: guest error (delivering): {}", e);
|
||||
EventVerdict::Deliver
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn req_close(&mut self, conn_id: u64, sub_id: &str) {
|
||||
if let Some(subs) = self.runtimes.get_mut(&conn_id) {
|
||||
subs.remove(sub_id);
|
||||
if subs.is_empty() {
|
||||
self.runtimes.remove(&conn_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn conn_close(&mut self, conn_id: u64) {
|
||||
self.runtimes.remove(&conn_id);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -41,14 +41,14 @@ impl UnparsedNote {
|
||||
self.0.get().len()
|
||||
}
|
||||
|
||||
/// Fully parse the event into a [`Note`]. Only used by a filter that
|
||||
/// Fully parse the event into a [`Note`]. Only used when a guest filter
|
||||
/// actually needs the event's fields.
|
||||
pub fn parse(&self) -> serde_json::Result<Note> {
|
||||
serde_json::from_str(self.0.get())
|
||||
}
|
||||
|
||||
/// Cheaply parse just the event `id` for the accept-list, avoiding a full
|
||||
/// [`Note`] parse on the bandwidth-only path.
|
||||
/// [`Note`] parse on the bandwidth-only (no-guest) path.
|
||||
pub fn id(&self) -> serde_json::Result<String> {
|
||||
#[derive(Deserialize)]
|
||||
struct IdOnly {
|
||||
|
||||
+8
-1
@@ -45,6 +45,9 @@ use serde::Deserialize;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{self, BufRead, Write};
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
use crate::readfilters::NScriptRead;
|
||||
|
||||
/// The `[readpolicy]` config table (read from `noteguard.toml`, or the file
|
||||
/// named by `$NOTEGUARD_CONFIG`). Mirrors the write-side `Config`: an ordered
|
||||
/// `pipeline` of filter names plus a `filters` map of each filter's own config.
|
||||
@@ -113,10 +116,14 @@ impl ReadPolicy {
|
||||
);
|
||||
}
|
||||
|
||||
/// All built-in read filters, available on every new [`ReadPolicy`].
|
||||
/// All built-in read filters, available on every new [`ReadPolicy`]. The
|
||||
/// guest (`nscript`) filter is registered only in `nscript` builds.
|
||||
fn register_builtin_filters(&mut self) {
|
||||
self.register_filter::<MaxEventsPerConn>();
|
||||
self.register_filter::<ReadBandwidth>();
|
||||
|
||||
#[cfg(feature = "nscript")]
|
||||
self.register_filter::<NScriptRead>();
|
||||
}
|
||||
|
||||
/// Compose the pipeline from config. Unlike the write side (which panics on a
|
||||
|
||||
Reference in New Issue
Block a user