feat(premium): recurring tiered relay-posting subscription (premium-post)

A paid premium tier gating GENERAL Nostr posting to the operator's relay, while
wallet-functional events (encrypted DMs, tips, swap coordination) stay free for
registered users. Registration itself stays free (PoW-gated). Off by default.

- Admission: a new `premium-post` write policy gates on kind x membership —
  premium author -> any kind; registered + WALLET_KINDS (1059 gift-wrap, 10050
  DM-relay-list) -> free; registered + general -> premium required; external ->
  gift-wrap DM inbox only. nauthz resolves is_premium_npub (only under premium-post),
  fail-closed.
- Payment: reuses the PaymentProvider seam (PULL model, non-custodial — only reads
  invoice status). POST /premium/invoice {plan} mints a tier invoice bound to the
  JWT user_id; POST /premium/activate verifies Settled + consumes single-use AND
  extends premium_until in ONE transaction (a mid-flight failure keeps the paid
  invoice redeemable); GET /premium/status reads it. Per-user pending-invoice cap.
- Tiered plans (PREMIUM_PLANS id:days:amount) = a built-in discount feature;
  advertised via /capabilities (premium_relay + premium{currency,plans,relay_url}).
- Config fail-closes: PREMIUM_ENABLED needs relay on + premium-post + processor
  creds + >=1 positive-decimal plan + unique ids + days<=3660, and the 0-conf /
  expiry processor floors apply on the premium path too (its common case is
  require_payment=false).
- Tests: 15 policy unit (incl. 5 premium-post) + config fail-closed matrix + plan
  parser + L1 integration (activate single-use/stacking/cross-user, is_premium by
  expiry, feature gate). OpenAPI + migration updated.

Adversarially reviewed (correctness / security-payment / operational-config); the
0-conf-on-premium-path double-spend footgun, non-transactional activate, and
unbounded plan days were caught and fixed before commit.
This commit is contained in:
jwinterm
2026-07-02 17:56:44 -04:00
parent b4935b15e8
commit eb98e4d625
15 changed files with 1339 additions and 27 deletions
+46
View File
@@ -47,6 +47,8 @@ pub struct FeatureCapabilities {
pub nostr_identity: bool,
/// First-party Nostr relay (encrypted DM inbox). See `messaging` for details.
pub nostr_relay: bool,
/// Paid premium tier for general Nostr posting to the relay. See `premium`.
pub premium_relay: bool,
/// Tipping (parked).
pub tips: bool,
}
@@ -66,6 +68,26 @@ pub struct MessagingCapability {
pub supported_nips: Vec<u16>,
}
/// A single premium plan (discount tier): `days` of relay-posting access for
/// `amount` in [`PremiumCapability::currency`].
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct PremiumPlanInfo {
pub id: String,
pub days: i32,
pub amount: String,
}
/// Premium tier details (present only when `features.premium_relay`). The wallet
/// renders the plan tiers (discount visible) and gates general-Nostr posting to
/// the Smirk relay on the user's premium status; wallet events stay free.
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct PremiumCapability {
pub currency: String,
pub plans: Vec<PremiumPlanInfo>,
/// The relay premium posting targets (mirrors `messaging.relay_url`).
pub relay_url: String,
}
/// This instance's wallet-restore (import) policy. The wallet uses it to adapt
/// its import UX — hide/grey the restore-height field under `create-only`, warn
/// when a chosen date exceeds the bound. `max_depth_days` is present only for
@@ -117,6 +139,9 @@ pub struct CapabilitiesResponse {
/// First-party Nostr relay details; present only when `features.nostr_relay`.
#[serde(skip_serializing_if = "Option::is_none")]
pub messaging: Option<MessagingCapability>,
/// Premium tier details; present only when `features.premium_relay`.
#[serde(skip_serializing_if = "Option::is_none")]
pub premium: Option<PremiumCapability>,
}
/// Whether an enabled chain can actually be served (its infra secret/URL is
@@ -176,6 +201,7 @@ pub fn effective_capabilities(config: &Config) -> CapabilitiesResponse {
// Relay advertised only when enabled AND a URL is configured (config
// presence downgrade — never advertise a relay clients can't reach).
nostr_relay: relay_advertised(config),
premium_relay: premium_advertised(config),
tips: config.features.tips,
},
restore: RestoreCapability {
@@ -212,6 +238,20 @@ pub fn effective_capabilities(config: &Config) -> CapabilitiesResponse {
supported_nips: crate::infra::relay::SUPPORTED_NIPS.to_vec(),
}
}),
premium: premium_advertised(config).then(|| PremiumCapability {
currency: config.premium.currency.clone(),
plans: config
.premium
.plans
.iter()
.map(|p| PremiumPlanInfo {
id: p.id.clone(),
days: p.days,
amount: p.amount.clone(),
})
.collect(),
relay_url: config.messaging.relay.advertised_url.clone(),
}),
}
}
@@ -222,6 +262,12 @@ fn relay_advertised(config: &Config) -> bool {
config.messaging.relay.enabled && !config.messaging.relay.advertised_url.trim().is_empty()
}
/// Whether the premium tier is enabled AND the relay it gates is advertised
/// (config validation already couples premium to relay + the premium-post policy).
fn premium_advertised(config: &Config) -> bool {
config.premium.enabled && relay_advertised(config)
}
/// Describe this instance's enabled chains and features.
#[utoipa::path(
get,
+1
View File
@@ -9,6 +9,7 @@ pub mod landing;
pub mod middleware;
pub mod nip05;
pub mod openapi;
pub mod premium;
pub mod prices;
pub mod users;
pub mod wallet;
+11 -1
View File
@@ -62,6 +62,9 @@ use utoipa::OpenApi;
crate::api::wallet::grin_relay::cancel,
crate::api::wallet::heights::heights,
crate::api::nip05::well_known_nostr,
crate::api::premium::invoice,
crate::api::premium::activate,
crate::api::premium::status,
),
components(schemas(
crate::api::health::HealthResponse,
@@ -72,6 +75,8 @@ use utoipa::OpenApi;
crate::api::capabilities::RestoreCapability,
crate::api::capabilities::RegistrationCapability,
crate::api::capabilities::MessagingCapability,
crate::api::capabilities::PremiumCapability,
crate::api::capabilities::PremiumPlanInfo,
crate::api::prices::PricesResponse,
crate::api::auth::AuthResponse,
crate::api::auth::UserInfo,
@@ -143,6 +148,10 @@ use utoipa::OpenApi;
crate::api::wallet::grin_relay::PendingRelaysResponse,
crate::api::wallet::heights::HeightsResponse,
crate::api::nip05::WellKnownResponse,
crate::api::premium::InvoiceReq,
crate::api::premium::InvoiceResp,
crate::api::premium::ActivateReq,
crate::api::premium::StatusResp,
)),
tags(
(name = "system", description = "Service health and metadata."),
@@ -151,7 +160,8 @@ use utoipa::OpenApi;
(name = "btc_ltc", description = "Bitcoin/Litecoin chain access via Electrum (balance, UTXOs, history, tip, fee, broadcast)."),
(name = "xmr_wow", description = "Monero/Wownero chain access via LWS (register, balance, history, unspent/random outs, submit, height, confirmations)."),
(name = "grin", description = "Grin view-only chain access (rewind_hash scan, tip height, broadcast)."),
(name = "grin_relay", description = "Grin slatepack relay: async non-custodial mailbox for interactive Grin transfers (feature-flagged).")
(name = "grin_relay", description = "Grin slatepack relay: async non-custodial mailbox for interactive Grin transfers (feature-flagged)."),
(name = "premium", description = "Premium subscription: mint a tier invoice, activate on settlement, read status (feature-flagged).")
)
)]
pub struct ApiDoc;
+260
View File
@@ -0,0 +1,260 @@
//! Premium subscription endpoints — recurring, tiered access to the operator's
//! Nostr relay for general posting (the `premium-post` write policy). Reuses the
//! registration PaymentProvider: `POST /premium/invoice` mints a tier invoice,
//! `POST /premium/activate` verifies settlement (PULL model) and extends the
//! caller's premium window, `GET /premium/status` reports it. Non-custodial — the
//! backend only READS invoice status, never holds funds.
use std::sync::Arc;
use axum::{
extract::State,
http::HeaderMap,
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use tracing::{info, instrument};
use crate::api::middleware::extract_user_id_from_token;
use crate::error::AppError;
use crate::infra::payment::{InvoiceRequest, InvoiceStatus};
use crate::AppState;
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct InvoiceReq {
/// Plan id (see `/capabilities` → `premium.plans`), e.g. `quarter`.
pub plan: String,
}
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct InvoiceResp {
pub invoice_id: String,
/// Where to pay (a checkout URL or address).
pub pay_to: String,
pub plan: String,
pub amount: String,
pub currency: String,
}
#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct ActivateReq {
pub invoice_id: String,
}
#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct StatusResp {
/// Whether the caller currently holds active premium.
pub active: bool,
/// Premium expiry (RFC3339), or null if never premium / lapsed.
pub premium_until: Option<String>,
}
/// Reject when the premium tier is not enabled on this instance.
fn ensure_enabled(state: &AppState) -> Result<(), AppError> {
if state.config.premium.enabled {
Ok(())
} else {
Err(AppError::ValidationError(
"Premium is not available on this instance.".into(),
))
}
}
/// Mint a premium invoice for a chosen plan, bound to the caller.
#[utoipa::path(
security(("bearer_auth" = [])),
post,
path = "/premium/invoice",
request_body = InvoiceReq,
responses(
(status = 200, description = "Invoice minted", body = InvoiceResp),
(status = 400, description = "Premium off or unknown plan"),
(status = 401, description = "Missing or invalid token")
),
tag = "premium"
)]
#[instrument(skip(state, headers))]
pub async fn invoice(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
Json(req): Json<InvoiceReq>,
) -> Result<Json<InvoiceResp>, AppError> {
let user_id = extract_user_id_from_token(&state, &headers).await?;
ensure_enabled(&state)?;
let plan = state
.config
.premium
.plans
.iter()
.find(|p| p.id == req.plan)
.ok_or_else(|| AppError::ValidationError("Unknown premium plan.".into()))?;
// Cap outstanding unconsumed invoices per user — each mints a real processor
// invoice, so bound the self-authenticated amplification into the processor.
const MAX_PENDING: i64 = 8;
if state.db.count_unconsumed_premium_invoices(user_id).await? >= MAX_PENDING {
return Err(AppError::ValidationError(
"Too many pending premium invoices; pay or let them expire before minting another."
.into(),
));
}
let provider = state
.payment
.as_ref()
.ok_or_else(|| AppError::Internal("payment provider not configured".into()))?;
let pay = &state.config.registration.payment;
let currency = state.config.premium.currency.clone();
let invoice = provider
.create_invoice(&InvoiceRequest {
amount: plan.amount.clone(),
currency: currency.clone(),
confirmations: pay.confirmations,
bind: user_id.to_string(),
expires_minutes: pay.expires_minutes,
})
.await?;
state
.db
.insert_premium_invoice(
&invoice.id,
user_id,
provider.kind(),
&plan.id,
plan.days,
&plan.amount,
&currency,
)
.await?;
Ok(Json(InvoiceResp {
invoice_id: invoice.id,
pay_to: invoice.pay_to,
plan: plan.id.clone(),
amount: plan.amount.clone(),
currency,
}))
}
/// Verify a settled premium invoice and extend the caller's premium window.
#[utoipa::path(
security(("bearer_auth" = [])),
post,
path = "/premium/activate",
request_body = ActivateReq,
responses(
(status = 200, description = "Premium extended", body = StatusResp),
(status = 400, description = "Unknown, unpaid, or already-used invoice"),
(status = 401, description = "Missing or invalid token")
),
tag = "premium"
)]
#[instrument(skip(state, headers))]
pub async fn activate(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
Json(req): Json<ActivateReq>,
) -> Result<Json<StatusResp>, AppError> {
let user_id = extract_user_id_from_token(&state, &headers).await?;
ensure_enabled(&state)?;
let provider = state
.payment
.as_ref()
.ok_or_else(|| AppError::Internal("payment provider not configured".into()))?;
let id = req.invoice_id.trim();
let uid = user_id.to_string();
// Binding precheck (local DB): must exist, be bound to THIS user, and unspent.
// A missing row and a row bound to a different user collapse to one error.
let row = match state.db.get_premium_invoice(id).await? {
Some(r) if r.user_id == user_id => r,
_ => {
return Err(AppError::ValidationError(
"Unknown or invalid premium invoice.".into(),
))
}
};
if row.consumed_at.is_some() {
return Err(AppError::ValidationError(
"This premium invoice has already been used.".into(),
));
}
// Source of truth: the processor. Only Settled grants (paid in full per policy).
let inv = provider.get_invoice(id).await?;
if inv.status != InvoiceStatus::Settled {
return Err(AppError::ValidationError(
"Payment not yet confirmed. Complete the payment and retry.".into(),
));
}
// Defence-in-depth: the settled invoice's metadata bind must match this user.
if let Some(ref bound) = inv.bind {
if bound != &uid {
return Err(AppError::ValidationError(
"Unknown or invalid premium invoice.".into(),
));
}
}
// Atomic single-use consume + extend (one transaction — a mid-flight failure
// rolls back so the paid invoice stays redeemable). None = already used/raced.
let until = match state
.db
.activate_premium(id, user_id, row.period_days)
.await?
{
Some(u) => u,
None => {
return Err(AppError::ValidationError(
"This premium invoice has already been used.".into(),
))
}
};
info!(
days = row.period_days,
"premium invoice settled + activated; window extended"
);
Ok(Json(StatusResp {
active: true,
premium_until: Some(until.to_rfc3339()),
}))
}
/// The caller's current premium status.
#[utoipa::path(
security(("bearer_auth" = [])),
get,
path = "/premium/status",
responses(
(status = 200, description = "Premium status", body = StatusResp),
(status = 401, description = "Missing or invalid token")
),
tag = "premium"
)]
#[instrument(skip(state, headers))]
pub async fn status(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
) -> Result<Json<StatusResp>, AppError> {
let user_id = extract_user_id_from_token(&state, &headers).await?;
let until = state.db.get_premium_until(user_id).await?;
let active = until.map(|u| u > chrono::Utc::now()).unwrap_or(false);
Ok(Json(StatusResp {
active,
premium_until: until.map(|u| u.to_rfc3339()),
}))
}
pub fn routes() -> Router<Arc<AppState>> {
Router::new()
.route("/premium/invoice", post(invoice))
.route("/premium/activate", post(activate))
.route("/premium/status", get(status))
}