forked from coracle/caravel
Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f23ba5ee00 | |||
| 29f657635c | |||
| 9556a34b19 | |||
| 3ecd285290 | |||
| 9f8fe7261f | |||
| 1aeb15971d | |||
| 48f20dc1a5 |
@@ -28,5 +28,6 @@ LIVEKIT_API_SECRET=
|
|||||||
|
|
||||||
# Billing
|
# Billing
|
||||||
NWC_URL= # Nostr Wallet Connect URL for generating Lightning invoices
|
NWC_URL= # Nostr Wallet Connect URL for generating Lightning invoices
|
||||||
|
ENCRYPTION_SECRET= # Nostr secret key (hex or nsec) used for NIP-44 encryption of tenant nwc_url at rest
|
||||||
STRIPE_SECRET_KEY= # Required Stripe API secret key (sk_...)
|
STRIPE_SECRET_KEY= # Required Stripe API secret key (sk_...)
|
||||||
STRIPE_WEBHOOK_SECRET=whsec_test_00000000000000000000000000 # Webhook signing secret (use real value in production)
|
STRIPE_WEBHOOK_SECRET=whsec_test_00000000000000000000000000 # Webhook signing secret (use real value in production)
|
||||||
|
|||||||
+24
-23
@@ -30,29 +30,30 @@ backend/
|
|||||||
|
|
||||||
Environment variables:
|
Environment variables:
|
||||||
|
|
||||||
| Variable | Description | Default |
|
| Variable | Description | Default |
|
||||||
| ------------------------ | ----------------------------------------------------------------------- | ------------------------------------ |
|
| ------------------------ | --------------------------------------------------------------------------------------- | ---------------------------------------- |
|
||||||
| `DATABASE_URL` | SQLite URL. Relative paths are resolved under `backend/`. | `sqlite://<backend>/data/caravel.db` |
|
| `DATABASE_URL` | SQLite URL. Relative paths are resolved under `backend/`. | `sqlite://<backend>/data/caravel.db` |
|
||||||
| `HOST` | API bind host (also used for NIP-98 `u` host check) | `127.0.0.1` |
|
| `HOST` | API bind host (also used for NIP-98 `u` host check) | `127.0.0.1` |
|
||||||
| `PORT` | API bind port | `2892` |
|
| `PORT` | API bind port | `2892` |
|
||||||
| `ADMINS` | Comma-separated admin pubkeys (hex) | _optional_ |
|
| `ADMINS` | Comma-separated admin pubkeys (hex) | _optional_ |
|
||||||
| `ALLOW_ORIGINS` | Comma-separated CORS origins. If empty, CORS is permissive. | _optional_ |
|
| `ALLOW_ORIGINS` | Comma-separated CORS origins. If empty, CORS is permissive. | _optional_ |
|
||||||
| `ZOOID_API_URL` | Zooid API base URL used by infra worker | _required for infra sync_ |
|
| `ZOOID_API_URL` | Zooid API base URL used by infra worker | _required for infra sync_ |
|
||||||
| `ZOOID_API_SECRET` | Nostr secret key used for authentication of requests to the zooid API | _required_ |
|
| `ZOOID_API_SECRET` | Nostr secret key used for authentication of requests to the zooid API | _required_ |
|
||||||
| `RELAY_DOMAIN` | Base domain appended to relay subdomains | empty |
|
| `RELAY_DOMAIN` | Base domain appended to relay subdomains | empty |
|
||||||
| `LIVEKIT_URL` | LiveKit URL sent to zooid when relay livekit is enabled | _optional_ |
|
| `LIVEKIT_URL` | LiveKit URL sent to zooid when relay livekit is enabled | _optional_ |
|
||||||
| `LIVEKIT_API_KEY` | LiveKit API key sent to zooid | _optional_ |
|
| `LIVEKIT_API_KEY` | LiveKit API key sent to zooid | _optional_ |
|
||||||
| `LIVEKIT_API_SECRET` | LiveKit API secret sent to zooid | _optional_ |
|
| `LIVEKIT_API_SECRET` | LiveKit API secret sent to zooid | _optional_ |
|
||||||
| `NWC_URL` | Platform NWC URL used to generate BOLT11 invoices | _required for invoice generation_ |
|
| `NWC_URL` | Platform NWC URL used to generate BOLT11 invoices | _required for invoice generation_ |
|
||||||
| `STRIPE_SECRET_KEY` | Stripe API secret key used for billing API operations | _required_ |
|
| `ENCRYPTION_SECRET` | Nostr secret key (hex or `nsec`) used for NIP-44 encryption of tenant `nwc_url` at rest | _required when tenant `nwc_url` is used_ |
|
||||||
| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret used to verify `Stripe-Signature` headers | _required_ |
|
| `STRIPE_SECRET_KEY` | Stripe API secret key used for billing API operations | _required_ |
|
||||||
| `ROBOT_SECRET` | Robot Nostr secret key | _required_ |
|
| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret used to verify `Stripe-Signature` headers | _required_ |
|
||||||
| `ROBOT_NAME` | Robot display name (kind `0`) | _optional_ |
|
| `ROBOT_SECRET` | Robot Nostr secret key | _required_ |
|
||||||
| `ROBOT_DESCRIPTION` | Robot description (kind `0`) | _optional_ |
|
| `ROBOT_NAME` | Robot display name (kind `0`) | _optional_ |
|
||||||
| `ROBOT_PICTURE` | Robot picture URL (kind `0`) | _optional_ |
|
| `ROBOT_DESCRIPTION` | Robot description (kind `0`) | _optional_ |
|
||||||
| `ROBOT_OUTBOX_RELAYS` | Comma-separated relays published as kind `10002` | _required_ |
|
| `ROBOT_PICTURE` | Robot picture URL (kind `0`) | _optional_ |
|
||||||
| `ROBOT_INDEXER_RELAYS` | Comma-separated relays used for recipient relay discovery | _required_ |
|
| `ROBOT_OUTBOX_RELAYS` | Comma-separated relays published as kind `10002` | _required_ |
|
||||||
| `ROBOT_MESSAGING_RELAYS` | Comma-separated relays published as kind `10050` | _required_ |
|
| `ROBOT_INDEXER_RELAYS` | Comma-separated relays used for recipient relay discovery | _required_ |
|
||||||
|
| `ROBOT_MESSAGING_RELAYS` | Comma-separated relays published as kind `10050` | _required_ |
|
||||||
|
|
||||||
Relay list env vars are comma-separated and trimmed. If a relay has no `ws://` or `wss://` scheme, `wss://` is prepended.
|
Relay list env vars are comma-separated and trimmed. If a relay has no `ws://` or `wss://` scheme, `wss://` is prepended.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS invoice_nwc_payment (
|
||||||
|
invoice_id TEXT PRIMARY KEY,
|
||||||
|
tenant_pubkey TEXT NOT NULL,
|
||||||
|
state TEXT NOT NULL CHECK (state IN ('pending', 'paid')),
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (tenant_pubkey) REFERENCES tenant(pubkey)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_invoice_nwc_payment_tenant_pubkey
|
||||||
|
ON invoice_nwc_payment (tenant_pubkey);
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS invoice_manual_lightning_payment (
|
||||||
|
invoice_id TEXT PRIMARY KEY,
|
||||||
|
tenant_pubkey TEXT NOT NULL,
|
||||||
|
bolt11 TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
updated_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (tenant_pubkey) REFERENCES tenant(pubkey)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_invoice_manual_lightning_payment_tenant_pubkey
|
||||||
|
ON invoice_manual_lightning_payment (tenant_pubkey);
|
||||||
+53
-7
@@ -445,6 +445,17 @@ struct IdentityResponse {
|
|||||||
is_admin: bool,
|
is_admin: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
struct TenantResponse {
|
||||||
|
pubkey: String,
|
||||||
|
nwc_configured: bool,
|
||||||
|
nwc_error: Option<String>,
|
||||||
|
created_at: i64,
|
||||||
|
stripe_customer_id: String,
|
||||||
|
stripe_subscription_id: Option<String>,
|
||||||
|
past_due_at: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct CreateRelayRequest {
|
struct CreateRelayRequest {
|
||||||
tenant: String,
|
tenant: String,
|
||||||
@@ -486,7 +497,7 @@ async fn list_tenants(
|
|||||||
state.api.require_admin(&pubkey)?;
|
state.api.require_admin(&pubkey)?;
|
||||||
|
|
||||||
match state.api.query.list_tenants().await {
|
match state.api.query.list_tenants().await {
|
||||||
Ok(tenants) => Ok(ok(StatusCode::OK, tenants)),
|
Ok(tenants) => Ok(ok(StatusCode::OK, scrub_tenants_for_response(tenants))),
|
||||||
Err(e) => Ok(err(
|
Err(e) => Ok(err(
|
||||||
StatusCode::INTERNAL_SERVER_ERROR,
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
"internal",
|
"internal",
|
||||||
@@ -515,7 +526,7 @@ async fn create_tenant(
|
|||||||
let pubkey = state.api.extract_auth_pubkey(&headers)?;
|
let pubkey = state.api.extract_auth_pubkey(&headers)?;
|
||||||
|
|
||||||
match state.api.query.get_tenant(&pubkey).await {
|
match state.api.query.get_tenant(&pubkey).await {
|
||||||
Ok(Some(t)) => Ok(ok(StatusCode::OK, t)),
|
Ok(Some(t)) => Ok(ok(StatusCode::OK, scrub_tenant_for_response(t))),
|
||||||
Ok(None) => {
|
Ok(None) => {
|
||||||
let stripe_customer_id = match state.api.billing.stripe_create_customer(&pubkey).await {
|
let stripe_customer_id = match state.api.billing.stripe_create_customer(&pubkey).await {
|
||||||
Ok(id) => id,
|
Ok(id) => id,
|
||||||
@@ -539,10 +550,10 @@ async fn create_tenant(
|
|||||||
};
|
};
|
||||||
|
|
||||||
match state.api.command.create_tenant(&tenant).await {
|
match state.api.command.create_tenant(&tenant).await {
|
||||||
Ok(()) => Ok(ok(StatusCode::OK, tenant)),
|
Ok(()) => Ok(ok(StatusCode::OK, scrub_tenant_for_response(tenant))),
|
||||||
Err(e) if matches!(map_unique_error(&e), Some("pubkey-exists")) => {
|
Err(e) if matches!(map_unique_error(&e), Some("pubkey-exists")) => {
|
||||||
match state.api.query.get_tenant(&pubkey).await {
|
match state.api.query.get_tenant(&pubkey).await {
|
||||||
Ok(Some(t)) => Ok(ok(StatusCode::OK, t)),
|
Ok(Some(t)) => Ok(ok(StatusCode::OK, scrub_tenant_for_response(t))),
|
||||||
Ok(None) => Ok(err(
|
Ok(None) => Ok(err(
|
||||||
StatusCode::INTERNAL_SERVER_ERROR,
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
"internal",
|
"internal",
|
||||||
@@ -585,7 +596,7 @@ async fn get_tenant(
|
|||||||
let auth = state.api.extract_auth_pubkey(&headers)?;
|
let auth = state.api.extract_auth_pubkey(&headers)?;
|
||||||
state.api.require_admin_or_tenant(&auth, &pubkey)?;
|
state.api.require_admin_or_tenant(&auth, &pubkey)?;
|
||||||
let tenant = state.api.get_tenant_or_404(&pubkey).await?;
|
let tenant = state.api.get_tenant_or_404(&pubkey).await?;
|
||||||
Ok(ok(StatusCode::OK, tenant))
|
Ok(ok(StatusCode::OK, scrub_tenant_for_response(tenant)))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn list_relays(
|
async fn list_relays(
|
||||||
@@ -1009,6 +1020,13 @@ async fn get_invoice(
|
|||||||
.map_err(map_invoice_lookup_error)?;
|
.map_err(map_invoice_lookup_error)?;
|
||||||
state.api.require_admin_or_tenant(&auth, &tenant.pubkey)?;
|
state.api.require_admin_or_tenant(&auth, &tenant.pubkey)?;
|
||||||
|
|
||||||
|
let invoice = state
|
||||||
|
.api
|
||||||
|
.billing
|
||||||
|
.reconcile_manual_lightning_invoice(&id, &invoice)
|
||||||
|
.await
|
||||||
|
.map_err(map_invoice_lookup_error)?;
|
||||||
|
|
||||||
Ok(ok(StatusCode::OK, invoice))
|
Ok(ok(StatusCode::OK, invoice))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1026,6 +1044,13 @@ async fn get_invoice_bolt11(
|
|||||||
.map_err(map_invoice_lookup_error)?;
|
.map_err(map_invoice_lookup_error)?;
|
||||||
state.api.require_admin_or_tenant(&auth, &tenant.pubkey)?;
|
state.api.require_admin_or_tenant(&auth, &tenant.pubkey)?;
|
||||||
|
|
||||||
|
let invoice = state
|
||||||
|
.api
|
||||||
|
.billing
|
||||||
|
.reconcile_manual_lightning_invoice(&id, &invoice)
|
||||||
|
.await
|
||||||
|
.map_err(map_invoice_lookup_error)?;
|
||||||
|
|
||||||
let status = invoice["status"].as_str().unwrap_or_default();
|
let status = invoice["status"].as_str().unwrap_or_default();
|
||||||
if status != "open" {
|
if status != "open" {
|
||||||
return Ok(err(
|
return Ok(err(
|
||||||
@@ -1038,7 +1063,12 @@ async fn get_invoice_bolt11(
|
|||||||
let amount_due = invoice["amount_due"].as_i64().unwrap_or(0);
|
let amount_due = invoice["amount_due"].as_i64().unwrap_or(0);
|
||||||
let currency = invoice["currency"].as_str().unwrap_or("usd");
|
let currency = invoice["currency"].as_str().unwrap_or("usd");
|
||||||
|
|
||||||
match state.api.billing.create_bolt11(amount_due, currency).await {
|
match state
|
||||||
|
.api
|
||||||
|
.billing
|
||||||
|
.get_or_create_manual_lightning_bolt11(&id, &tenant.pubkey, amount_due, currency)
|
||||||
|
.await
|
||||||
|
{
|
||||||
Ok(bolt11) => Ok(ok(StatusCode::OK, serde_json::json!({ "bolt11": bolt11 }))),
|
Ok(bolt11) => Ok(ok(StatusCode::OK, serde_json::json!({ "bolt11": bolt11 }))),
|
||||||
Err(e) => Ok(err(
|
Err(e) => Ok(err(
|
||||||
StatusCode::INTERNAL_SERVER_ERROR,
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
@@ -1103,7 +1133,7 @@ async fn update_tenant(
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Ok(ok(StatusCode::OK, tenant))
|
Ok(ok(StatusCode::OK, scrub_tenant_for_response(tenant)))
|
||||||
}
|
}
|
||||||
Err(e) => Ok(err(
|
Err(e) => Ok(err(
|
||||||
StatusCode::INTERNAL_SERVER_ERROR,
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
@@ -1112,3 +1142,19 @@ async fn update_tenant(
|
|||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn scrub_tenant_for_response(tenant: Tenant) -> TenantResponse {
|
||||||
|
TenantResponse {
|
||||||
|
pubkey: tenant.pubkey,
|
||||||
|
nwc_configured: !tenant.nwc_url.is_empty(),
|
||||||
|
nwc_error: tenant.nwc_error,
|
||||||
|
created_at: tenant.created_at,
|
||||||
|
stripe_customer_id: tenant.stripe_customer_id,
|
||||||
|
stripe_subscription_id: tenant.stripe_subscription_id,
|
||||||
|
past_due_at: tenant.past_due_at,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scrub_tenants_for_response(tenants: Vec<Tenant>) -> Vec<TenantResponse> {
|
||||||
|
tenants.into_iter().map(scrub_tenant_for_response).collect()
|
||||||
|
}
|
||||||
|
|||||||
+372
-43
@@ -1,7 +1,8 @@
|
|||||||
use anyhow::{Result, anyhow};
|
use anyhow::{Result, anyhow};
|
||||||
use hmac::{Hmac, Mac};
|
use hmac::{Hmac, Mac};
|
||||||
use nwc::prelude::{
|
use nwc::prelude::{
|
||||||
MakeInvoiceRequest, NWC, NostrWalletConnectURI, PayInvoiceRequest as NwcPayInvoiceRequest,
|
LookupInvoiceRequest, LookupInvoiceResponse, MakeInvoiceRequest, NWC, NostrWalletConnectURI,
|
||||||
|
PayInvoiceRequest as NwcPayInvoiceRequest, TransactionState,
|
||||||
};
|
};
|
||||||
use sha2::Sha256;
|
use sha2::Sha256;
|
||||||
|
|
||||||
@@ -17,6 +18,9 @@ type HmacSha256 = Hmac<Sha256>;
|
|||||||
const STRIPE_API: &str = "https://api.stripe.com/v1";
|
const STRIPE_API: &str = "https://api.stripe.com/v1";
|
||||||
const COINBASE_SPOT_API: &str = "https://api.coinbase.com/v2/prices";
|
const COINBASE_SPOT_API: &str = "https://api.coinbase.com/v2/prices";
|
||||||
const WEBHOOK_TOLERANCE_SECS: i64 = 300;
|
const WEBHOOK_TOLERANCE_SECS: i64 = 300;
|
||||||
|
const MANUAL_LIGHTNING_PAYMENT_DM: &str = "Payment is due for your relay subscription. Please visit the application to complete a manual Lightning payment.";
|
||||||
|
const NWC_ERROR_DM_PREFIX: &str = "NWC auto-payment failed:";
|
||||||
|
const NWC_ERROR_DM_MAX_CHARS: usize = 240;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum InvoiceLookupError {
|
pub enum InvoiceLookupError {
|
||||||
@@ -75,12 +79,17 @@ struct CoinbaseSpotPriceData {
|
|||||||
amount: String,
|
amount: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum NwcInvoicePaymentOutcome {
|
||||||
|
Paid,
|
||||||
|
Fallback(anyhow::Error),
|
||||||
|
Pending(anyhow::Error),
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Billing {
|
pub struct Billing {
|
||||||
nwc_url: String,
|
nwc_url: String,
|
||||||
stripe_secret_key: String,
|
stripe_secret_key: String,
|
||||||
stripe_webhook_secret: String,
|
stripe_webhook_secret: String,
|
||||||
btc_quote_api_base: String,
|
|
||||||
http: reqwest::Client,
|
http: reqwest::Client,
|
||||||
query: Query,
|
query: Query,
|
||||||
command: Command,
|
command: Command,
|
||||||
@@ -98,13 +107,10 @@ impl Billing {
|
|||||||
if stripe_webhook_secret.trim().is_empty() {
|
if stripe_webhook_secret.trim().is_empty() {
|
||||||
panic!("missing STRIPE_WEBHOOK_SECRET environment variable");
|
panic!("missing STRIPE_WEBHOOK_SECRET environment variable");
|
||||||
}
|
}
|
||||||
let btc_quote_api_base =
|
|
||||||
std::env::var("BTC_PRICE_API_BASE").unwrap_or_else(|_| COINBASE_SPOT_API.to_string());
|
|
||||||
Self {
|
Self {
|
||||||
nwc_url,
|
nwc_url,
|
||||||
stripe_secret_key,
|
stripe_secret_key,
|
||||||
stripe_webhook_secret,
|
stripe_webhook_secret,
|
||||||
btc_quote_api_base,
|
|
||||||
http: reqwest::Client::new(),
|
http: reqwest::Client::new(),
|
||||||
query,
|
query,
|
||||||
command,
|
command,
|
||||||
@@ -115,6 +121,10 @@ impl Billing {
|
|||||||
pub async fn start(self) {
|
pub async fn start(self) {
|
||||||
let mut rx = self.command.notify.subscribe();
|
let mut rx = self.command.notify.subscribe();
|
||||||
|
|
||||||
|
if let Err(error) = self.reconcile_relay_subscriptions("startup").await {
|
||||||
|
tracing::error!(error = %error, "failed to reconcile relay billing state on startup");
|
||||||
|
}
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
match rx.recv().await {
|
match rx.recv().await {
|
||||||
Ok(activity) => {
|
Ok(activity) => {
|
||||||
@@ -124,12 +134,43 @@ impl Billing {
|
|||||||
}
|
}
|
||||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
|
Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
|
||||||
tracing::warn!(missed = n, "billing lagged");
|
tracing::warn!(missed = n, "billing lagged");
|
||||||
|
|
||||||
|
if let Err(error) = self.reconcile_relay_subscriptions("lagged").await {
|
||||||
|
tracing::error!(error = %error, "failed to reconcile relay billing state after lag");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
|
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn reconcile_relay_subscriptions(&self, source: &str) -> Result<()> {
|
||||||
|
let relays = self.query.list_relays().await?;
|
||||||
|
|
||||||
|
if relays.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
source,
|
||||||
|
relay_count = relays.len(),
|
||||||
|
"reconciling relay billing state"
|
||||||
|
);
|
||||||
|
|
||||||
|
for relay in relays {
|
||||||
|
if let Err(error) = self.sync_relay_subscription_for_relay(&relay).await {
|
||||||
|
tracing::error!(
|
||||||
|
source,
|
||||||
|
relay = %relay.id,
|
||||||
|
error = %error,
|
||||||
|
"failed to reconcile relay billing state"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
async fn handle_activity(&self, activity: &Activity) -> Result<()> {
|
async fn handle_activity(&self, activity: &Activity) -> Result<()> {
|
||||||
let needs_billing_sync = matches!(
|
let needs_billing_sync = matches!(
|
||||||
activity.activity_type.as_str(),
|
activity.activity_type.as_str(),
|
||||||
@@ -153,6 +194,10 @@ impl Billing {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
|
|
||||||
|
self.sync_relay_subscription_for_relay(&relay).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn sync_relay_subscription_for_relay(&self, relay: &Relay) -> Result<()> {
|
||||||
let Some(tenant) = self.query.get_tenant(&relay.tenant).await? else {
|
let Some(tenant) = self.query.get_tenant(&relay.tenant).await? else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
@@ -261,6 +306,23 @@ impl Billing {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn existing_invoice_nwc_payment_outcome(
|
||||||
|
&self,
|
||||||
|
invoice_id: &str,
|
||||||
|
) -> Result<Option<NwcInvoicePaymentOutcome>> {
|
||||||
|
let state = self.query.get_invoice_nwc_payment_state(invoice_id).await?;
|
||||||
|
match state.as_deref() {
|
||||||
|
Some("paid") => Ok(Some(NwcInvoicePaymentOutcome::Paid)),
|
||||||
|
Some("pending") => Ok(Some(NwcInvoicePaymentOutcome::Pending(anyhow!(
|
||||||
|
"invoice {invoice_id} has a pending NWC reconciliation; refusing to create a new Lightning charge"
|
||||||
|
)))),
|
||||||
|
Some(other) => Err(anyhow!(
|
||||||
|
"unknown invoice_nwc_payment state '{other}' for invoice {invoice_id}"
|
||||||
|
)),
|
||||||
|
None => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn handle_webhook(&self, payload: &str, signature: &str) -> Result<()> {
|
pub async fn handle_webhook(&self, payload: &str, signature: &str) -> Result<()> {
|
||||||
self.verify_webhook_signature(payload, signature)?;
|
self.verify_webhook_signature(payload, signature)?;
|
||||||
|
|
||||||
@@ -360,24 +422,54 @@ impl Billing {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let mut nwc_error_for_dm: Option<String> = None;
|
||||||
|
|
||||||
// 1. NWC auto-pay: if the tenant has a nwc_url
|
// 1. NWC auto-pay: if the tenant has a nwc_url
|
||||||
if !tenant.nwc_url.is_empty() {
|
if !tenant.nwc_url.is_empty() {
|
||||||
match self
|
match self
|
||||||
.nwc_pay_invoice(amount_due, currency, &tenant.nwc_url)
|
.nwc_pay_invoice(
|
||||||
.await
|
invoice_id,
|
||||||
|
&tenant.pubkey,
|
||||||
|
amount_due,
|
||||||
|
currency,
|
||||||
|
&tenant.nwc_url,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
{
|
{
|
||||||
Ok(()) => {
|
NwcInvoicePaymentOutcome::Paid => {
|
||||||
self.stripe_pay_invoice_out_of_band(invoice_id).await?;
|
self.mark_invoice_paid_out_of_band_after_nwc(invoice_id, &tenant.pubkey)
|
||||||
self.command.clear_tenant_nwc_error(&tenant.pubkey).await?;
|
.await?;
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
Err(e) => {
|
NwcInvoicePaymentOutcome::Fallback(e) => {
|
||||||
let error_msg = format!("{e}");
|
let error_msg = format!("{e}");
|
||||||
self.command
|
self.command
|
||||||
.set_tenant_nwc_error(&tenant.pubkey, &error_msg)
|
.set_tenant_nwc_error(&tenant.pubkey, &error_msg)
|
||||||
.await?;
|
.await?;
|
||||||
|
tracing::warn!(
|
||||||
|
error = %e,
|
||||||
|
tenant_pubkey = %tenant.pubkey,
|
||||||
|
stripe_customer_id,
|
||||||
|
invoice_id,
|
||||||
|
"nwc auto-payment failed for invoice.created"
|
||||||
|
);
|
||||||
|
nwc_error_for_dm = summarize_nwc_error_for_dm(&error_msg);
|
||||||
// Fall through to next option
|
// Fall through to next option
|
||||||
}
|
}
|
||||||
|
NwcInvoicePaymentOutcome::Pending(e) => {
|
||||||
|
let error_msg = format!("{e}");
|
||||||
|
self.command
|
||||||
|
.set_tenant_nwc_error(&tenant.pubkey, &error_msg)
|
||||||
|
.await?;
|
||||||
|
tracing::error!(
|
||||||
|
error = %e,
|
||||||
|
tenant_pubkey = %tenant.pubkey,
|
||||||
|
stripe_customer_id,
|
||||||
|
invoice_id,
|
||||||
|
"nwc auto-payment requires reconciliation before retry"
|
||||||
|
);
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -390,12 +482,8 @@ impl Billing {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 3. Manual payment: send a DM
|
// 3. Manual payment: send a DM
|
||||||
self.robot
|
let dm_message = manual_lightning_payment_dm(nwc_error_for_dm.as_deref());
|
||||||
.send_dm(
|
self.robot.send_dm(&tenant.pubkey, &dm_message).await?;
|
||||||
&tenant.pubkey,
|
|
||||||
"Payment is due for your relay subscription. Please visit the application to complete a manual Lightning payment.",
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -635,14 +723,60 @@ impl Billing {
|
|||||||
Ok((invoice, tenant))
|
Ok((invoice, tenant))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn reconcile_manual_lightning_invoice(
|
||||||
|
&self,
|
||||||
|
invoice_id: &str,
|
||||||
|
invoice: &serde_json::Value,
|
||||||
|
) -> std::result::Result<serde_json::Value, InvoiceLookupError> {
|
||||||
|
self.reconcile_manual_lightning_invoice_if_settled(invoice_id, invoice)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_or_create_manual_lightning_bolt11(
|
||||||
|
&self,
|
||||||
|
invoice_id: &str,
|
||||||
|
tenant_pubkey: &str,
|
||||||
|
amount_due_minor: i64,
|
||||||
|
currency: &str,
|
||||||
|
) -> Result<String> {
|
||||||
|
if let Some(existing_bolt11) = self
|
||||||
|
.query
|
||||||
|
.get_invoice_manual_lightning_bolt11(invoice_id)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
return Ok(existing_bolt11);
|
||||||
|
}
|
||||||
|
|
||||||
|
let bolt11 = self.create_bolt11(amount_due_minor, currency).await?;
|
||||||
|
|
||||||
|
if self
|
||||||
|
.command
|
||||||
|
.insert_manual_lightning_invoice_payment(invoice_id, tenant_pubkey, &bolt11)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
return Ok(bolt11);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.query
|
||||||
|
.get_invoice_manual_lightning_bolt11(invoice_id)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| {
|
||||||
|
anyhow!(
|
||||||
|
"manual lightning payment row missing after insert race for invoice {invoice_id}"
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn stripe_create_customer(&self, tenant_pubkey: &str) -> Result<String> {
|
pub async fn stripe_create_customer(&self, tenant_pubkey: &str) -> Result<String> {
|
||||||
let short_pubkey: String = tenant_pubkey.chars().take(12).collect();
|
let short_pubkey: String = tenant_pubkey.chars().take(12).collect();
|
||||||
let display_name = format!("Caravel tenant {short_pubkey}");
|
let display_name = format!("Caravel tenant {short_pubkey}");
|
||||||
|
let idempotency_key = self.idempotency_key(&["create_customer", tenant_pubkey]);
|
||||||
|
|
||||||
let resp = self
|
let resp = self
|
||||||
.http
|
.http
|
||||||
.post(format!("{STRIPE_API}/customers"))
|
.post(format!("{STRIPE_API}/customers"))
|
||||||
.bearer_auth(&self.stripe_secret_key)
|
.bearer_auth(&self.stripe_secret_key)
|
||||||
|
.header("Idempotency-Key", idempotency_key)
|
||||||
.form(&[
|
.form(&[
|
||||||
("name", display_name.as_str()),
|
("name", display_name.as_str()),
|
||||||
("metadata[tenant_pubkey]", tenant_pubkey),
|
("metadata[tenant_pubkey]", tenant_pubkey),
|
||||||
@@ -743,21 +877,28 @@ impl Billing {
|
|||||||
}
|
}
|
||||||
|
|
||||||
match self
|
match self
|
||||||
.nwc_pay_invoice(amount_due, currency, &tenant.nwc_url)
|
.nwc_pay_invoice(
|
||||||
.await
|
invoice_id,
|
||||||
|
&tenant.pubkey,
|
||||||
|
amount_due,
|
||||||
|
currency,
|
||||||
|
&tenant.nwc_url,
|
||||||
|
)
|
||||||
|
.await?
|
||||||
{
|
{
|
||||||
Ok(()) => {
|
NwcInvoicePaymentOutcome::Paid => {
|
||||||
if let Err(e) = self.stripe_pay_invoice_out_of_band(invoice_id).await {
|
if let Err(e) = self
|
||||||
|
.mark_invoice_paid_out_of_band_after_nwc(invoice_id, &tenant.pubkey)
|
||||||
|
.await
|
||||||
|
{
|
||||||
tracing::error!(
|
tracing::error!(
|
||||||
error = %e,
|
error = %e,
|
||||||
invoice_id,
|
invoice_id,
|
||||||
"failed to mark invoice paid out of band"
|
"failed to mark invoice paid out of band"
|
||||||
);
|
);
|
||||||
} else {
|
|
||||||
let _ = self.command.clear_tenant_nwc_error(&tenant.pubkey).await;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => {
|
NwcInvoicePaymentOutcome::Fallback(e) => {
|
||||||
let error_msg = format!("{e}");
|
let error_msg = format!("{e}");
|
||||||
tracing::error!(
|
tracing::error!(
|
||||||
error = %e,
|
error = %e,
|
||||||
@@ -769,6 +910,18 @@ impl Billing {
|
|||||||
.set_tenant_nwc_error(&tenant.pubkey, &error_msg)
|
.set_tenant_nwc_error(&tenant.pubkey, &error_msg)
|
||||||
.await;
|
.await;
|
||||||
}
|
}
|
||||||
|
NwcInvoicePaymentOutcome::Pending(e) => {
|
||||||
|
let error_msg = format!("{e}");
|
||||||
|
tracing::error!(
|
||||||
|
error = %e,
|
||||||
|
invoice_id,
|
||||||
|
"outstanding invoice requires NWC reconciliation before retry"
|
||||||
|
);
|
||||||
|
let _ = self
|
||||||
|
.command
|
||||||
|
.set_tenant_nwc_error(&tenant.pubkey, &error_msg)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -829,15 +982,29 @@ impl Billing {
|
|||||||
|
|
||||||
// --- Stripe API helpers ---
|
// --- Stripe API helpers ---
|
||||||
|
|
||||||
|
fn idempotency_key(&self, parts: &[&str]) -> String {
|
||||||
|
let mut mac = HmacSha256::new_from_slice(self.stripe_secret_key.as_bytes())
|
||||||
|
.expect("HMAC accepts any key length");
|
||||||
|
for (i, part) in parts.iter().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
mac.update(b":");
|
||||||
|
}
|
||||||
|
mac.update(part.as_bytes());
|
||||||
|
}
|
||||||
|
hex::encode(mac.finalize().into_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
async fn stripe_create_subscription(
|
async fn stripe_create_subscription(
|
||||||
&self,
|
&self,
|
||||||
customer_id: &str,
|
customer_id: &str,
|
||||||
price_id: &str,
|
price_id: &str,
|
||||||
) -> Result<(String, String)> {
|
) -> Result<(String, String)> {
|
||||||
|
let idempotency_key = self.idempotency_key(&["create_subscription", customer_id, price_id]);
|
||||||
let resp = self
|
let resp = self
|
||||||
.http
|
.http
|
||||||
.post(format!("{STRIPE_API}/subscriptions"))
|
.post(format!("{STRIPE_API}/subscriptions"))
|
||||||
.bearer_auth(&self.stripe_secret_key)
|
.bearer_auth(&self.stripe_secret_key)
|
||||||
|
.header("Idempotency-Key", idempotency_key)
|
||||||
.form(&[
|
.form(&[
|
||||||
("customer", customer_id),
|
("customer", customer_id),
|
||||||
("collection_method", "charge_automatically"),
|
("collection_method", "charge_automatically"),
|
||||||
@@ -864,10 +1031,13 @@ impl Billing {
|
|||||||
subscription_id: &str,
|
subscription_id: &str,
|
||||||
price_id: &str,
|
price_id: &str,
|
||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
|
let idempotency_key =
|
||||||
|
self.idempotency_key(&["create_subscription_item", subscription_id, price_id]);
|
||||||
let resp = self
|
let resp = self
|
||||||
.http
|
.http
|
||||||
.post(format!("{STRIPE_API}/subscription_items"))
|
.post(format!("{STRIPE_API}/subscription_items"))
|
||||||
.bearer_auth(&self.stripe_secret_key)
|
.bearer_auth(&self.stripe_secret_key)
|
||||||
|
.header("Idempotency-Key", idempotency_key)
|
||||||
.form(&[("subscription", subscription_id), ("price", price_id)])
|
.form(&[("subscription", subscription_id), ("price", price_id)])
|
||||||
.send()
|
.send()
|
||||||
.await?;
|
.await?;
|
||||||
@@ -886,10 +1056,13 @@ impl Billing {
|
|||||||
item_id: &str,
|
item_id: &str,
|
||||||
price_id: &str,
|
price_id: &str,
|
||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
|
let idempotency_key =
|
||||||
|
self.idempotency_key(&["update_subscription_item", item_id, price_id]);
|
||||||
let resp = self
|
let resp = self
|
||||||
.http
|
.http
|
||||||
.post(format!("{STRIPE_API}/subscription_items/{item_id}"))
|
.post(format!("{STRIPE_API}/subscription_items/{item_id}"))
|
||||||
.bearer_auth(&self.stripe_secret_key)
|
.bearer_auth(&self.stripe_secret_key)
|
||||||
|
.header("Idempotency-Key", idempotency_key)
|
||||||
.form(&[("price", price_id)])
|
.form(&[("price", price_id)])
|
||||||
.send()
|
.send()
|
||||||
.await?;
|
.await?;
|
||||||
@@ -926,9 +1099,11 @@ impl Billing {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn stripe_pay_invoice(&self, invoice_id: &str) -> Result<()> {
|
async fn stripe_pay_invoice(&self, invoice_id: &str) -> Result<()> {
|
||||||
|
let idempotency_key = self.idempotency_key(&["pay_invoice", invoice_id]);
|
||||||
self.http
|
self.http
|
||||||
.post(format!("{STRIPE_API}/invoices/{invoice_id}/pay"))
|
.post(format!("{STRIPE_API}/invoices/{invoice_id}/pay"))
|
||||||
.bearer_auth(&self.stripe_secret_key)
|
.bearer_auth(&self.stripe_secret_key)
|
||||||
|
.header("Idempotency-Key", idempotency_key)
|
||||||
.send()
|
.send()
|
||||||
.await?
|
.await?
|
||||||
.error_for_status()?;
|
.error_for_status()?;
|
||||||
@@ -968,9 +1143,11 @@ impl Billing {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn stripe_pay_invoice_out_of_band(&self, invoice_id: &str) -> Result<()> {
|
async fn stripe_pay_invoice_out_of_band(&self, invoice_id: &str) -> Result<()> {
|
||||||
|
let idempotency_key = self.idempotency_key(&["pay_invoice_oob", invoice_id]);
|
||||||
self.http
|
self.http
|
||||||
.post(format!("{STRIPE_API}/invoices/{invoice_id}/pay"))
|
.post(format!("{STRIPE_API}/invoices/{invoice_id}/pay"))
|
||||||
.bearer_auth(&self.stripe_secret_key)
|
.bearer_auth(&self.stripe_secret_key)
|
||||||
|
.header("Idempotency-Key", idempotency_key)
|
||||||
.form(&[("paid_out_of_band", "true")])
|
.form(&[("paid_out_of_band", "true")])
|
||||||
.send()
|
.send()
|
||||||
.await?
|
.await?
|
||||||
@@ -999,19 +1176,113 @@ impl Billing {
|
|||||||
|
|
||||||
// --- NWC helpers ---
|
// --- NWC helpers ---
|
||||||
|
|
||||||
|
async fn mark_invoice_paid_out_of_band_after_nwc(
|
||||||
|
&self,
|
||||||
|
invoice_id: &str,
|
||||||
|
tenant_pubkey: &str,
|
||||||
|
) -> Result<()> {
|
||||||
|
self.stripe_pay_invoice_out_of_band(invoice_id).await?;
|
||||||
|
self.command.clear_tenant_nwc_error(tenant_pubkey).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn reconcile_manual_lightning_invoice_if_settled(
|
||||||
|
&self,
|
||||||
|
invoice_id: &str,
|
||||||
|
invoice: &serde_json::Value,
|
||||||
|
) -> std::result::Result<serde_json::Value, InvoiceLookupError> {
|
||||||
|
if invoice["status"].as_str().unwrap_or_default() != "open" {
|
||||||
|
return Ok(invoice.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(bolt11) = self
|
||||||
|
.query
|
||||||
|
.get_invoice_manual_lightning_bolt11(invoice_id)
|
||||||
|
.await?
|
||||||
|
else {
|
||||||
|
return Ok(invoice.clone());
|
||||||
|
};
|
||||||
|
|
||||||
|
let settled = match self.is_manual_lightning_invoice_settled(&bolt11).await {
|
||||||
|
Ok(settled) => settled,
|
||||||
|
Err(error) => {
|
||||||
|
tracing::warn!(
|
||||||
|
error = %error,
|
||||||
|
invoice_id,
|
||||||
|
"failed to lookup manual lightning invoice settlement"
|
||||||
|
);
|
||||||
|
return Ok(invoice.clone());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if !settled {
|
||||||
|
return Ok(invoice.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Err(error) = self.stripe_pay_invoice_out_of_band(invoice_id).await {
|
||||||
|
tracing::warn!(
|
||||||
|
error = %error,
|
||||||
|
invoice_id,
|
||||||
|
"failed to mark settled manual lightning invoice as paid_out_of_band"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
self.stripe_get_invoice(invoice_id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn is_manual_lightning_invoice_settled(&self, bolt11: &str) -> Result<bool> {
|
||||||
|
let system_uri = Self::parse_nwc_uri(&self.nwc_url, "system")?;
|
||||||
|
let system_nwc = NWC::new(system_uri);
|
||||||
|
|
||||||
|
let lookup_req = LookupInvoiceRequest {
|
||||||
|
payment_hash: None,
|
||||||
|
invoice: Some(bolt11.to_string()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let lookup_result = system_nwc.lookup_invoice(lookup_req).await;
|
||||||
|
system_nwc.shutdown().await;
|
||||||
|
|
||||||
|
let lookup_response =
|
||||||
|
lookup_result.map_err(|error| anyhow!("failed to lookup invoice: {error}"))?;
|
||||||
|
|
||||||
|
Ok(Self::lookup_invoice_response_is_settled(&lookup_response))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lookup_invoice_response_is_settled(response: &LookupInvoiceResponse) -> bool {
|
||||||
|
response.state == Some(TransactionState::Settled) || response.settled_at.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_nwc_uri(nwc_url: &str, role: &str) -> Result<NostrWalletConnectURI> {
|
||||||
|
nwc_url
|
||||||
|
.parse::<NostrWalletConnectURI>()
|
||||||
|
.map_err(|_| anyhow!("invalid {role} NWC URL"))
|
||||||
|
}
|
||||||
|
|
||||||
async fn nwc_pay_invoice(
|
async fn nwc_pay_invoice(
|
||||||
&self,
|
&self,
|
||||||
|
invoice_id: &str,
|
||||||
|
tenant_pubkey: &str,
|
||||||
amount_due_minor: i64,
|
amount_due_minor: i64,
|
||||||
currency: &str,
|
currency: &str,
|
||||||
tenant_nwc_url: &str,
|
tenant_nwc_url: &str,
|
||||||
) -> Result<()> {
|
) -> Result<NwcInvoicePaymentOutcome> {
|
||||||
let amount_msats = self.fiat_minor_to_msats(amount_due_minor, currency).await?;
|
if let Some(existing_outcome) = self
|
||||||
|
.existing_invoice_nwc_payment_outcome(invoice_id)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
return Ok(existing_outcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
let amount_msats = match self.fiat_minor_to_msats(amount_due_minor, currency).await {
|
||||||
|
Ok(amount_msats) => amount_msats,
|
||||||
|
Err(error) => return Ok(NwcInvoicePaymentOutcome::Fallback(error)),
|
||||||
|
};
|
||||||
|
|
||||||
// Create a bolt11 invoice using the system wallet (self.nwc_url)
|
// Create a bolt11 invoice using the system wallet (self.nwc_url)
|
||||||
let system_uri: NostrWalletConnectURI = self
|
let system_uri = match Self::parse_nwc_uri(&self.nwc_url, "system") {
|
||||||
.nwc_url
|
Ok(system_uri) => system_uri,
|
||||||
.parse()
|
Err(error) => return Ok(NwcInvoicePaymentOutcome::Fallback(error)),
|
||||||
.map_err(|_| anyhow!("invalid system NWC URL"))?;
|
};
|
||||||
let system_nwc = NWC::new(system_uri);
|
let system_nwc = NWC::new(system_uri);
|
||||||
|
|
||||||
let make_req = MakeInvoiceRequest {
|
let make_req = MakeInvoiceRequest {
|
||||||
@@ -1021,29 +1292,61 @@ impl Billing {
|
|||||||
expiry: None,
|
expiry: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let invoice_response = system_nwc
|
let invoice_response = system_nwc.make_invoice(make_req).await;
|
||||||
.make_invoice(make_req)
|
|
||||||
.await
|
let invoice_response = match invoice_response {
|
||||||
.map_err(|e| anyhow!("failed to create invoice: {e}"))?;
|
Ok(invoice_response) => invoice_response,
|
||||||
|
Err(error) => {
|
||||||
|
system_nwc.shutdown().await;
|
||||||
|
return Ok(NwcInvoicePaymentOutcome::Fallback(anyhow!(
|
||||||
|
"failed to create invoice: {error}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
system_nwc.shutdown().await;
|
system_nwc.shutdown().await;
|
||||||
|
|
||||||
// Pay the bolt11 invoice using the tenant's wallet
|
// Pay the bolt11 invoice using the tenant's wallet
|
||||||
let tenant_uri: NostrWalletConnectURI = tenant_nwc_url
|
let tenant_uri = match Self::parse_nwc_uri(tenant_nwc_url, "tenant") {
|
||||||
.parse()
|
Ok(tenant_uri) => tenant_uri,
|
||||||
.map_err(|_| anyhow!("invalid tenant NWC URL"))?;
|
Err(error) => return Ok(NwcInvoicePaymentOutcome::Fallback(error)),
|
||||||
|
};
|
||||||
|
|
||||||
|
if !self
|
||||||
|
.command
|
||||||
|
.insert_pending_invoice_nwc_payment(invoice_id, tenant_pubkey)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
if let Some(existing_outcome) = self
|
||||||
|
.existing_invoice_nwc_payment_outcome(invoice_id)
|
||||||
|
.await?
|
||||||
|
{
|
||||||
|
return Ok(existing_outcome);
|
||||||
|
}
|
||||||
|
return Err(anyhow!(
|
||||||
|
"invoice_nwc_payment row missing after insert race for invoice {invoice_id}"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
let tenant_nwc = NWC::new(tenant_uri);
|
let tenant_nwc = NWC::new(tenant_uri);
|
||||||
|
|
||||||
let pay_req = NwcPayInvoiceRequest::new(invoice_response.invoice);
|
let pay_req = NwcPayInvoiceRequest::new(invoice_response.invoice);
|
||||||
|
|
||||||
tenant_nwc
|
let pay_result = tenant_nwc.pay_invoice(pay_req).await;
|
||||||
.pay_invoice(pay_req)
|
|
||||||
.await
|
|
||||||
.map_err(|e| anyhow!("failed to pay invoice: {e}"))?;
|
|
||||||
|
|
||||||
tenant_nwc.shutdown().await;
|
tenant_nwc.shutdown().await;
|
||||||
|
|
||||||
Ok(())
|
match pay_result {
|
||||||
|
Ok(_) => match self.command.mark_invoice_nwc_payment_paid(invoice_id).await {
|
||||||
|
Ok(()) => Ok(NwcInvoicePaymentOutcome::Paid),
|
||||||
|
Err(error) => Ok(NwcInvoicePaymentOutcome::Pending(anyhow!(
|
||||||
|
"invoice {invoice_id} was charged over NWC but failed to persist paid state: {error}"
|
||||||
|
))),
|
||||||
|
},
|
||||||
|
Err(error) => Ok(NwcInvoicePaymentOutcome::Pending(anyhow!(
|
||||||
|
"invoice {invoice_id} NWC payment attempt requires reconciliation: {error}"
|
||||||
|
))),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn fiat_minor_to_msats(&self, amount_due_minor: i64, currency: &str) -> Result<u64> {
|
async fn fiat_minor_to_msats(&self, amount_due_minor: i64, currency: &str) -> Result<u64> {
|
||||||
@@ -1057,7 +1360,7 @@ impl Billing {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn fetch_btc_spot_price(&self, currency: &str) -> Result<f64> {
|
async fn fetch_btc_spot_price(&self, currency: &str) -> Result<f64> {
|
||||||
fetch_btc_spot_price_from_base(&self.http, &self.btc_quote_api_base, currency).await
|
fetch_btc_spot_price_from_base(&self.http, COINBASE_SPOT_API, currency).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn currency_minor_exponent(currency: &str) -> Result<u8> {
|
fn currency_minor_exponent(currency: &str) -> Result<u8> {
|
||||||
@@ -1101,6 +1404,31 @@ pub async fn fetch_btc_spot_price_from_base(
|
|||||||
Ok(amount)
|
Ok(amount)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn summarize_nwc_error_for_dm(error: &str) -> Option<String> {
|
||||||
|
let normalized = error.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||||
|
if normalized.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
if normalized.chars().count() <= NWC_ERROR_DM_MAX_CHARS {
|
||||||
|
return Some(normalized);
|
||||||
|
}
|
||||||
|
|
||||||
|
let prefix_len = NWC_ERROR_DM_MAX_CHARS.saturating_sub(3);
|
||||||
|
let mut truncated = normalized.chars().take(prefix_len).collect::<String>();
|
||||||
|
truncated.push_str("...");
|
||||||
|
Some(truncated)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn manual_lightning_payment_dm(nwc_error: Option<&str>) -> String {
|
||||||
|
match nwc_error {
|
||||||
|
Some(error) if !error.is_empty() => {
|
||||||
|
format!("{MANUAL_LIGHTNING_PAYMENT_DM}\n\n{NWC_ERROR_DM_PREFIX} {error}")
|
||||||
|
}
|
||||||
|
_ => MANUAL_LIGHTNING_PAYMENT_DM.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn fiat_minor_to_msats_from_quote(
|
pub fn fiat_minor_to_msats_from_quote(
|
||||||
amount_due_minor: i64,
|
amount_due_minor: i64,
|
||||||
currency: &str,
|
currency: &str,
|
||||||
@@ -1399,3 +1727,4 @@ mod tests {
|
|||||||
assert_eq!(billing.stripe_webhook_secret, "whsec_test_dummy");
|
assert_eq!(billing.stripe_webhook_secret, "whsec_test_dummy");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+74
-7
@@ -2,6 +2,7 @@ use anyhow::Result;
|
|||||||
use sqlx::{Sqlite, SqlitePool, Transaction};
|
use sqlx::{Sqlite, SqlitePool, Transaction};
|
||||||
use tokio::sync::broadcast;
|
use tokio::sync::broadcast;
|
||||||
|
|
||||||
|
use crate::crypto;
|
||||||
use crate::models::{
|
use crate::models::{
|
||||||
Activity, RELAY_STATUS_ACTIVE, RELAY_STATUS_DELINQUENT, RELAY_STATUS_INACTIVE, Relay, Tenant,
|
Activity, RELAY_STATUS_ACTIVE, RELAY_STATUS_DELINQUENT, RELAY_STATUS_INACTIVE, Relay, Tenant,
|
||||||
};
|
};
|
||||||
@@ -70,6 +71,7 @@ impl Command {
|
|||||||
anyhow::bail!("stripe_customer_id is required");
|
anyhow::bail!("stripe_customer_id is required");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let encrypted_nwc_url = crypto::encrypt(&tenant.nwc_url)?;
|
||||||
let mut tx = self.pool.begin().await?;
|
let mut tx = self.pool.begin().await?;
|
||||||
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
@@ -77,7 +79,7 @@ impl Command {
|
|||||||
VALUES (?, ?, ?, ?)",
|
VALUES (?, ?, ?, ?)",
|
||||||
)
|
)
|
||||||
.bind(&tenant.pubkey)
|
.bind(&tenant.pubkey)
|
||||||
.bind(&tenant.nwc_url)
|
.bind(&encrypted_nwc_url)
|
||||||
.bind(tenant.created_at)
|
.bind(tenant.created_at)
|
||||||
.bind(&tenant.stripe_customer_id)
|
.bind(&tenant.stripe_customer_id)
|
||||||
.execute(&mut *tx)
|
.execute(&mut *tx)
|
||||||
@@ -92,10 +94,11 @@ impl Command {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn update_tenant(&self, tenant: &Tenant) -> Result<()> {
|
pub async fn update_tenant(&self, tenant: &Tenant) -> Result<()> {
|
||||||
|
let encrypted_nwc_url = crypto::encrypt(&tenant.nwc_url)?;
|
||||||
let mut tx = self.pool.begin().await?;
|
let mut tx = self.pool.begin().await?;
|
||||||
|
|
||||||
sqlx::query("UPDATE tenant SET nwc_url = ? WHERE pubkey = ?")
|
sqlx::query("UPDATE tenant SET nwc_url = ? WHERE pubkey = ?")
|
||||||
.bind(&tenant.nwc_url)
|
.bind(&encrypted_nwc_url)
|
||||||
.bind(&tenant.pubkey)
|
.bind(&tenant.pubkey)
|
||||||
.execute(&mut *tx)
|
.execute(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -113,12 +116,12 @@ impl Command {
|
|||||||
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO relay (
|
"INSERT INTO relay (
|
||||||
id, tenant, schema, subdomain, plan, status, sync_error,
|
id, tenant, schema, subdomain, plan, status, synced, sync_error,
|
||||||
info_name, info_icon, info_description,
|
info_name, info_icon, info_description,
|
||||||
policy_public_join, policy_strip_signatures,
|
policy_public_join, policy_strip_signatures,
|
||||||
groups_enabled, management_enabled, blossom_enabled,
|
groups_enabled, management_enabled, blossom_enabled,
|
||||||
livekit_enabled, push_enabled
|
livekit_enabled, push_enabled
|
||||||
) VALUES (?, ?, ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
) VALUES (?, ?, ?, ?, ?, 'active', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
)
|
)
|
||||||
.bind(&relay.id)
|
.bind(&relay.id)
|
||||||
.bind(&relay.tenant)
|
.bind(&relay.tenant)
|
||||||
@@ -151,7 +154,7 @@ impl Command {
|
|||||||
|
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"UPDATE relay
|
"UPDATE relay
|
||||||
SET tenant = ?, schema = ?, subdomain = ?, plan = ?, status = ?, sync_error = ?,
|
SET tenant = ?, schema = ?, subdomain = ?, plan = ?, status = ?, sync_error = ?, synced = 0,
|
||||||
info_name = ?, info_icon = ?, info_description = ?,
|
info_name = ?, info_icon = ?, info_description = ?,
|
||||||
policy_public_join = ?, policy_strip_signatures = ?,
|
policy_public_join = ?, policy_strip_signatures = ?,
|
||||||
groups_enabled = ?, management_enabled = ?, blossom_enabled = ?,
|
groups_enabled = ?, management_enabled = ?, blossom_enabled = ?,
|
||||||
@@ -203,7 +206,7 @@ impl Command {
|
|||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let mut tx = self.pool.begin().await?;
|
let mut tx = self.pool.begin().await?;
|
||||||
|
|
||||||
sqlx::query("UPDATE relay SET status = ? WHERE id = ?")
|
sqlx::query("UPDATE relay SET status = ?, synced = 0 WHERE id = ?")
|
||||||
.bind(status)
|
.bind(status)
|
||||||
.bind(relay_id)
|
.bind(relay_id)
|
||||||
.execute(&mut *tx)
|
.execute(&mut *tx)
|
||||||
@@ -224,7 +227,7 @@ impl Command {
|
|||||||
pub async fn fail_relay_sync(&self, relay: &Relay, sync_error: String) -> Result<()> {
|
pub async fn fail_relay_sync(&self, relay: &Relay, sync_error: String) -> Result<()> {
|
||||||
let mut tx = self.pool.begin().await?;
|
let mut tx = self.pool.begin().await?;
|
||||||
|
|
||||||
sqlx::query("UPDATE relay SET sync_error = ? WHERE id = ?")
|
sqlx::query("UPDATE relay SET synced = 0, sync_error = ? WHERE id = ?")
|
||||||
.bind(&sync_error)
|
.bind(&sync_error)
|
||||||
.bind(&relay.id)
|
.bind(&relay.id)
|
||||||
.execute(&mut *tx)
|
.execute(&mut *tx)
|
||||||
@@ -313,6 +316,70 @@ impl Command {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn insert_pending_invoice_nwc_payment(
|
||||||
|
&self,
|
||||||
|
invoice_id: &str,
|
||||||
|
tenant_pubkey: &str,
|
||||||
|
) -> Result<bool> {
|
||||||
|
let now = chrono::Utc::now().timestamp();
|
||||||
|
let result = sqlx::query(
|
||||||
|
"INSERT INTO invoice_nwc_payment (invoice_id, tenant_pubkey, state, created_at, updated_at)
|
||||||
|
VALUES (?, ?, 'pending', ?, ?)
|
||||||
|
ON CONFLICT(invoice_id) DO NOTHING",
|
||||||
|
)
|
||||||
|
.bind(invoice_id)
|
||||||
|
.bind(tenant_pubkey)
|
||||||
|
.bind(now)
|
||||||
|
.bind(now)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(result.rows_affected() > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn mark_invoice_nwc_payment_paid(&self, invoice_id: &str) -> Result<()> {
|
||||||
|
let now = chrono::Utc::now().timestamp();
|
||||||
|
let result = sqlx::query(
|
||||||
|
"UPDATE invoice_nwc_payment
|
||||||
|
SET state = 'paid', updated_at = ?
|
||||||
|
WHERE invoice_id = ?",
|
||||||
|
)
|
||||||
|
.bind(now)
|
||||||
|
.bind(invoice_id)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if result.rows_affected() == 0 {
|
||||||
|
anyhow::bail!("invoice_nwc_payment row missing for invoice_id: {invoice_id}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn insert_manual_lightning_invoice_payment(
|
||||||
|
&self,
|
||||||
|
invoice_id: &str,
|
||||||
|
tenant_pubkey: &str,
|
||||||
|
bolt11: &str,
|
||||||
|
) -> Result<bool> {
|
||||||
|
let now = chrono::Utc::now().timestamp();
|
||||||
|
let result = sqlx::query(
|
||||||
|
"INSERT INTO invoice_manual_lightning_payment
|
||||||
|
(invoice_id, tenant_pubkey, bolt11, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT(invoice_id) DO NOTHING",
|
||||||
|
)
|
||||||
|
.bind(invoice_id)
|
||||||
|
.bind(tenant_pubkey)
|
||||||
|
.bind(bolt11)
|
||||||
|
.bind(now)
|
||||||
|
.bind(now)
|
||||||
|
.execute(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(result.rows_affected() > 0)
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn set_tenant_past_due(&self, pubkey: &str) -> Result<()> {
|
pub async fn set_tenant_past_due(&self, pubkey: &str) -> Result<()> {
|
||||||
let now = chrono::Utc::now().timestamp();
|
let now = chrono::Utc::now().timestamp();
|
||||||
sqlx::query("UPDATE tenant SET past_due_at = ? WHERE pubkey = ?")
|
sqlx::query("UPDATE tenant SET past_due_at = ? WHERE pubkey = ?")
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
use anyhow::{Result, anyhow};
|
||||||
|
use nostr_sdk::prelude::{Keys, nip44};
|
||||||
|
|
||||||
|
const ENVELOPE_PREFIX: &str = "enc:nip44:v2:";
|
||||||
|
|
||||||
|
pub fn encrypt(value: &str) -> Result<String> {
|
||||||
|
if value.is_empty() {
|
||||||
|
return Ok(String::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
let keys = parse_encryption_keys()?;
|
||||||
|
let payload = nip44::encrypt(
|
||||||
|
keys.secret_key(),
|
||||||
|
&keys.public_key(),
|
||||||
|
value,
|
||||||
|
nip44::Version::V2,
|
||||||
|
)
|
||||||
|
.map_err(|e| anyhow!("encrypt failed: {e}"))?;
|
||||||
|
|
||||||
|
Ok(format!("{ENVELOPE_PREFIX}{payload}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decrypt(value: &str) -> Result<String> {
|
||||||
|
if value.is_empty() {
|
||||||
|
return Ok(String::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(payload) = value.strip_prefix(ENVELOPE_PREFIX) else {
|
||||||
|
return Ok(value.to_string());
|
||||||
|
};
|
||||||
|
|
||||||
|
let keys = parse_encryption_keys()?;
|
||||||
|
nip44::decrypt(keys.secret_key(), &keys.public_key(), payload)
|
||||||
|
.map_err(|e| anyhow!("decrypt failed: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_encryption_keys() -> Result<Keys> {
|
||||||
|
let raw = std::env::var("ENCRYPTION_SECRET")
|
||||||
|
.map_err(|_| anyhow!("missing ENCRYPTION_SECRET environment variable"))?;
|
||||||
|
let trimmed = raw.trim();
|
||||||
|
|
||||||
|
if trimmed.is_empty() {
|
||||||
|
return Err(anyhow!("missing ENCRYPTION_SECRET environment variable"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Keys::parse(trimmed).map_err(|e| {
|
||||||
|
anyhow!("ENCRYPTION_SECRET must be a valid nostr secret key (hex or nsec): {e}")
|
||||||
|
})
|
||||||
|
}
|
||||||
+35
-7
@@ -53,8 +53,8 @@ impl Infra {
|
|||||||
pub async fn start(self) {
|
pub async fn start(self) {
|
||||||
let mut rx = self.command.notify.subscribe();
|
let mut rx = self.command.notify.subscribe();
|
||||||
|
|
||||||
if let Err(e) = self.schedule_startup_retries().await {
|
if let Err(error) = self.reconcile_relay_state("startup").await {
|
||||||
tracing::error!(error = %e, "failed to schedule relay sync retries on startup");
|
tracing::error!(error = %error, "failed to reconcile relay state on startup");
|
||||||
}
|
}
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
@@ -66,6 +66,10 @@ impl Infra {
|
|||||||
}
|
}
|
||||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
|
Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
|
||||||
tracing::warn!(missed = n, "infra lagged");
|
tracing::warn!(missed = n, "infra lagged");
|
||||||
|
|
||||||
|
if let Err(error) = self.reconcile_relay_state("lagged").await {
|
||||||
|
tracing::error!(error = %error, "failed to reconcile relay state after lag");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
|
Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
|
||||||
}
|
}
|
||||||
@@ -89,17 +93,32 @@ impl Infra {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
|
|
||||||
let is_new = relay.synced == 0;
|
let is_new = self.relay_sync_is_new(&relay).await?;
|
||||||
self.sync_and_report(&relay, is_new).await;
|
self.sync_and_report(&relay, is_new).await;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn schedule_startup_retries(&self) -> Result<()> {
|
async fn reconcile_relay_state(&self, source: &str) -> Result<()> {
|
||||||
let relays = self.query.list_relays_with_sync_error().await?;
|
let relays = self.query.list_relays_pending_sync().await?;
|
||||||
|
|
||||||
|
if relays.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
source,
|
||||||
|
relay_count = relays.len(),
|
||||||
|
"reconciling pending relay state"
|
||||||
|
);
|
||||||
|
|
||||||
for relay in relays {
|
for relay in relays {
|
||||||
self.schedule_relay_sync_retry(&relay.id, "startup").await?;
|
if relay.sync_error.trim().is_empty() {
|
||||||
|
let is_new = self.relay_sync_is_new(&relay).await?;
|
||||||
|
self.sync_and_report(&relay, is_new).await;
|
||||||
|
} else {
|
||||||
|
self.schedule_relay_sync_retry(&relay.id, source).await?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -151,11 +170,20 @@ impl Infra {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let is_new = relay.synced == 0;
|
let is_new = self.relay_sync_is_new(&relay).await?;
|
||||||
self.sync_and_report(&relay, is_new).await;
|
self.sync_and_report(&relay, is_new).await;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn relay_sync_is_new(&self, relay: &Relay) -> Result<bool> {
|
||||||
|
if relay.synced == 1 {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
let has_completed_sync = self.query.relay_has_completed_sync(&relay.id).await?;
|
||||||
|
Ok(!has_completed_sync)
|
||||||
|
}
|
||||||
|
|
||||||
async fn sync_and_report(&self, relay: &Relay, is_new: bool) {
|
async fn sync_and_report(&self, relay: &Relay, is_new: bool) {
|
||||||
match self.sync_relay(relay, is_new).await {
|
match self.sync_relay(relay, is_new).await {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
pub mod api;
|
pub mod api;
|
||||||
pub mod billing;
|
pub mod billing;
|
||||||
pub mod command;
|
pub mod command;
|
||||||
|
pub mod crypto;
|
||||||
pub mod infra;
|
pub mod infra;
|
||||||
pub mod models;
|
pub mod models;
|
||||||
pub mod pool;
|
pub mod pool;
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
mod api;
|
mod api;
|
||||||
mod billing;
|
mod billing;
|
||||||
mod command;
|
mod command;
|
||||||
|
mod crypto;
|
||||||
mod infra;
|
mod infra;
|
||||||
mod models;
|
mod models;
|
||||||
mod pool;
|
mod pool;
|
||||||
|
|||||||
+50
-5
@@ -1,6 +1,7 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use sqlx::SqlitePool;
|
use sqlx::SqlitePool;
|
||||||
|
|
||||||
|
use crate::crypto;
|
||||||
use crate::models::{Activity, Plan, Relay, Tenant};
|
use crate::models::{Activity, Plan, Relay, Tenant};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -21,7 +22,7 @@ impl Query {
|
|||||||
)
|
)
|
||||||
.fetch_all(&self.pool)
|
.fetch_all(&self.pool)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(rows)
|
rows.into_iter().map(decrypt_tenant_nwc_url).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_tenant(&self, pubkey: &str) -> Result<Option<Tenant>> {
|
pub async fn get_tenant(&self, pubkey: &str) -> Result<Option<Tenant>> {
|
||||||
@@ -33,7 +34,7 @@ impl Query {
|
|||||||
.bind(pubkey)
|
.bind(pubkey)
|
||||||
.fetch_optional(&self.pool)
|
.fetch_optional(&self.pool)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(row)
|
row.map(decrypt_tenant_nwc_url).transpose()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn list_plans() -> Vec<Plan> {
|
pub fn list_plans() -> Vec<Plan> {
|
||||||
@@ -94,7 +95,7 @@ impl Query {
|
|||||||
Ok(rows)
|
Ok(rows)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn list_relays_with_sync_error(&self) -> Result<Vec<Relay>> {
|
pub async fn list_relays_pending_sync(&self) -> Result<Vec<Relay>> {
|
||||||
let rows = sqlx::query_as::<_, Relay>(
|
let rows = sqlx::query_as::<_, Relay>(
|
||||||
"SELECT id, tenant, schema, subdomain, plan, stripe_subscription_item_id,
|
"SELECT id, tenant, schema, subdomain, plan, stripe_subscription_item_id,
|
||||||
status, sync_error,
|
status, sync_error,
|
||||||
@@ -103,7 +104,7 @@ impl Query {
|
|||||||
groups_enabled, management_enabled, blossom_enabled,
|
groups_enabled, management_enabled, blossom_enabled,
|
||||||
livekit_enabled, push_enabled, synced
|
livekit_enabled, push_enabled, synced
|
||||||
FROM relay
|
FROM relay
|
||||||
WHERE TRIM(sync_error) != ''
|
WHERE synced = 0 OR TRIM(sync_error) != ''
|
||||||
ORDER BY id",
|
ORDER BY id",
|
||||||
)
|
)
|
||||||
.fetch_all(&self.pool)
|
.fetch_all(&self.pool)
|
||||||
@@ -158,7 +159,30 @@ impl Query {
|
|||||||
.bind(stripe_customer_id)
|
.bind(stripe_customer_id)
|
||||||
.fetch_optional(&self.pool)
|
.fetch_optional(&self.pool)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(row)
|
row.map(decrypt_tenant_nwc_url).transpose()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_invoice_nwc_payment_state(&self, invoice_id: &str) -> Result<Option<String>> {
|
||||||
|
let state = sqlx::query_scalar::<_, String>(
|
||||||
|
"SELECT state FROM invoice_nwc_payment WHERE invoice_id = ?",
|
||||||
|
)
|
||||||
|
.bind(invoice_id)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Ok(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_invoice_manual_lightning_bolt11(
|
||||||
|
&self,
|
||||||
|
invoice_id: &str,
|
||||||
|
) -> Result<Option<String>> {
|
||||||
|
let bolt11 = sqlx::query_scalar::<_, String>(
|
||||||
|
"SELECT bolt11 FROM invoice_manual_lightning_payment WHERE invoice_id = ?",
|
||||||
|
)
|
||||||
|
.bind(invoice_id)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?;
|
||||||
|
Ok(bolt11)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn has_active_paid_relays(&self, tenant_id: &str) -> Result<bool> {
|
pub async fn has_active_paid_relays(&self, tenant_id: &str) -> Result<bool> {
|
||||||
@@ -184,4 +208,25 @@ impl Query {
|
|||||||
.await?;
|
.await?;
|
||||||
Ok(rows)
|
Ok(rows)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn relay_has_completed_sync(&self, relay_id: &str) -> Result<bool> {
|
||||||
|
let found = sqlx::query_scalar::<_, i64>(
|
||||||
|
"SELECT 1
|
||||||
|
FROM activity
|
||||||
|
WHERE resource_type = 'relay'
|
||||||
|
AND resource_id = ?
|
||||||
|
AND activity_type = 'complete_relay_sync'
|
||||||
|
LIMIT 1",
|
||||||
|
)
|
||||||
|
.bind(relay_id)
|
||||||
|
.fetch_optional(&self.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(found.is_some())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decrypt_tenant_nwc_url(mut tenant: Tenant) -> Result<Tenant> {
|
||||||
|
tenant.nwc_url = crypto::decrypt(&tenant.nwc_url)?;
|
||||||
|
Ok(tenant)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -99,6 +99,7 @@ export type UpdateRelayInput = {
|
|||||||
export type Tenant = {
|
export type Tenant = {
|
||||||
pubkey: string
|
pubkey: string
|
||||||
nwc_url: string
|
nwc_url: string
|
||||||
|
nwc_configured: boolean
|
||||||
created_at: number
|
created_at: number
|
||||||
stripe_customer_id: string
|
stripe_customer_id: string
|
||||||
stripe_subscription_id: string | null
|
stripe_subscription_id: string | null
|
||||||
|
|||||||
@@ -135,7 +135,7 @@ export const reactivateRelayById = (id: string) => reactivateRelay(id)
|
|||||||
|
|
||||||
export async function tenantNeedsPaymentSetup(): Promise<boolean> {
|
export async function tenantNeedsPaymentSetup(): Promise<boolean> {
|
||||||
const tenant = await getTenant(account()!.pubkey)
|
const tenant = await getTenant(account()!.pubkey)
|
||||||
return !tenant.nwc_url && !tenant.stripe_subscription_id
|
return !tenant.nwc_configured && !tenant.stripe_subscription_id
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getLatestOpenInvoice(): Promise<Invoice | null> {
|
export async function getLatestOpenInvoice(): Promise<Invoice | null> {
|
||||||
|
|||||||
@@ -18,9 +18,9 @@ export default function Account() {
|
|||||||
const invoicesLoading = useMinLoading(() => invoices.loading)
|
const invoicesLoading = useMinLoading(() => invoices.loading)
|
||||||
|
|
||||||
const hasBillingChanges = createMemo(() => {
|
const hasBillingChanges = createMemo(() => {
|
||||||
const current = tenant()?.nwc_url?.trim() ?? ""
|
|
||||||
const next = nwcUrl().trim()
|
const next = nwcUrl().trim()
|
||||||
return current !== next
|
if (next) return true
|
||||||
|
return tenant()?.nwc_configured ?? false
|
||||||
})
|
})
|
||||||
|
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
@@ -169,7 +169,7 @@ export default function Account() {
|
|||||||
<p class="text-xs text-gray-500 mt-0.5">{periodLabel()}</p>
|
<p class="text-xs text-gray-500 mt-0.5">{periodLabel()}</p>
|
||||||
</Show>
|
</Show>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center gap-2 flex-shrink-0">
|
<div class="flex items-center gap-2 shrink-0">
|
||||||
<Show when={isOpen()}>
|
<Show when={isOpen()}>
|
||||||
<span class="text-xs text-blue-600 font-medium">Pay now</span>
|
<span class="text-xs text-blue-600 font-medium">Pay now</span>
|
||||||
</Show>
|
</Show>
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ export default function RelayDetail() {
|
|||||||
if (!isPaidRelay()) return false
|
if (!isPaidRelay()) return false
|
||||||
const t = tenant()
|
const t = tenant()
|
||||||
if (!t) return false
|
if (!t) return false
|
||||||
return !t.nwc_url
|
return !t.nwc_configured
|
||||||
})
|
})
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
Reference in New Issue
Block a user