chore: encrypt tenant NWC URL at rest and stop secret exposure in tenant APIs

This commit is contained in:
2026-05-02 17:05:54 +05:45
parent b1e3747ddb
commit 18866b5cc8
12 changed files with 156 additions and 44 deletions
+1
View File
@@ -28,5 +28,6 @@ LIVEKIT_API_SECRET=
# Billing
NWC_URL= # Nostr Wallet Connect URL for generating Lightning invoices
NWC_URL_CIPHER_KEY= # 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_WEBHOOK_SECRET=whsec_test_00000000000000000000000000 # Webhook signing secret (use real value in production)
+24 -23
View File
@@ -30,29 +30,30 @@ backend/
Environment variables:
| Variable | Description | Default |
| ------------------------ | ----------------------------------------------------------------------- | ------------------------------------ |
| `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` |
| `PORT` | API bind port | `2892` |
| `ADMINS` | Comma-separated admin pubkeys (hex) | _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_SECRET` | Nostr secret key used for authentication of requests to the zooid API | _required_ |
| `RELAY_DOMAIN` | Base domain appended to relay subdomains | empty |
| `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_SECRET` | LiveKit API secret sent to zooid | _optional_ |
| `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_ |
| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret used to verify `Stripe-Signature` headers | _required_ |
| `ROBOT_SECRET` | Robot Nostr secret key | _required_ |
| `ROBOT_NAME` | Robot display name (kind `0`) | _optional_ |
| `ROBOT_DESCRIPTION` | Robot description (kind `0`) | _optional_ |
| `ROBOT_PICTURE` | Robot picture URL (kind `0`) | _optional_ |
| `ROBOT_OUTBOX_RELAYS` | Comma-separated relays published as kind `10002` | _required_ |
| `ROBOT_INDEXER_RELAYS` | Comma-separated relays used for recipient relay discovery | _required_ |
| `ROBOT_MESSAGING_RELAYS` | Comma-separated relays published as kind `10050` | _required_ |
| Variable | Description | Default |
| ------------------------ | --------------------------------------------------------------------------------------- | ---------------------------------------- |
| `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` |
| `PORT` | API bind port | `2892` |
| `ADMINS` | Comma-separated admin pubkeys (hex) | _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_SECRET` | Nostr secret key used for authentication of requests to the zooid API | _required_ |
| `RELAY_DOMAIN` | Base domain appended to relay subdomains | empty |
| `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_SECRET` | LiveKit API secret sent to zooid | _optional_ |
| `NWC_URL` | Platform NWC URL used to generate BOLT11 invoices | _required for invoice generation_ |
| `NWC_URL_CIPHER_KEY` | 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_SECRET_KEY` | Stripe API secret key used for billing API operations | _required_ |
| `STRIPE_WEBHOOK_SECRET` | Stripe webhook signing secret used to verify `Stripe-Signature` headers | _required_ |
| `ROBOT_SECRET` | Robot Nostr secret key | _required_ |
| `ROBOT_NAME` | Robot display name (kind `0`) | _optional_ |
| `ROBOT_DESCRIPTION` | Robot description (kind `0`) | _optional_ |
| `ROBOT_PICTURE` | Robot picture URL (kind `0`) | _optional_ |
| `ROBOT_OUTBOX_RELAYS` | Comma-separated relays published as kind `10002` | _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.
+35 -6
View File
@@ -445,6 +445,18 @@ struct IdentityResponse {
is_admin: bool,
}
#[derive(Serialize)]
struct TenantResponse {
pubkey: String,
nwc_url: 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)]
struct CreateRelayRequest {
tenant: String,
@@ -486,7 +498,7 @@ async fn list_tenants(
state.api.require_admin(&pubkey)?;
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(
StatusCode::INTERNAL_SERVER_ERROR,
"internal",
@@ -515,7 +527,7 @@ async fn create_tenant(
let pubkey = state.api.extract_auth_pubkey(&headers)?;
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) => {
let stripe_customer_id = match state.api.billing.stripe_create_customer(&pubkey).await {
Ok(id) => id,
@@ -539,10 +551,10 @@ async fn create_tenant(
};
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")) => {
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(
StatusCode::INTERNAL_SERVER_ERROR,
"internal",
@@ -585,7 +597,7 @@ async fn get_tenant(
let auth = state.api.extract_auth_pubkey(&headers)?;
state.api.require_admin_or_tenant(&auth, &pubkey)?;
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(
@@ -1122,7 +1134,7 @@ async fn update_tenant(
}
});
}
Ok(ok(StatusCode::OK, tenant))
Ok(ok(StatusCode::OK, scrub_tenant_for_response(tenant)))
}
Err(e) => Ok(err(
StatusCode::INTERNAL_SERVER_ERROR,
@@ -1131,3 +1143,20 @@ async fn update_tenant(
)),
}
}
fn scrub_tenant_for_response(tenant: Tenant) -> TenantResponse {
TenantResponse {
pubkey: tenant.pubkey,
nwc_url: String::new(),
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()
}
+6 -4
View File
@@ -151,7 +151,11 @@ impl Billing {
return Ok(());
}
tracing::info!(source, relay_count = relays.len(), "reconciling relay billing state");
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 {
@@ -995,8 +999,7 @@ impl Billing {
customer_id: &str,
price_id: &str,
) -> Result<(String, String)> {
let idempotency_key =
self.idempotency_key(&["create_subscription", customer_id, price_id]);
let idempotency_key = self.idempotency_key(&["create_subscription", customer_id, price_id]);
let resp = self
.http
.post(format!("{STRIPE_API}/subscriptions"))
@@ -1723,5 +1726,4 @@ mod tests {
assert_eq!(billing.stripe_secret_key, "sk_test_dummy");
assert_eq!(billing.stripe_webhook_secret, "whsec_test_dummy");
}
}
+4 -2
View File
@@ -70,6 +70,7 @@ impl Command {
anyhow::bail!("stripe_customer_id is required");
}
let encrypted_nwc_url = tenant.encrypted_nwc_url_for_storage()?;
let mut tx = self.pool.begin().await?;
sqlx::query(
@@ -77,7 +78,7 @@ impl Command {
VALUES (?, ?, ?, ?)",
)
.bind(&tenant.pubkey)
.bind(&tenant.nwc_url)
.bind(&encrypted_nwc_url)
.bind(tenant.created_at)
.bind(&tenant.stripe_customer_id)
.execute(&mut *tx)
@@ -92,10 +93,11 @@ impl Command {
}
pub async fn update_tenant(&self, tenant: &Tenant) -> Result<()> {
let encrypted_nwc_url = tenant.encrypted_nwc_url_for_storage()?;
let mut tx = self.pool.begin().await?;
sqlx::query("UPDATE tenant SET nwc_url = ? WHERE pubkey = ?")
.bind(&tenant.nwc_url)
.bind(&encrypted_nwc_url)
.bind(&tenant.pubkey)
.execute(&mut *tx)
.await?;
+5 -1
View File
@@ -106,7 +106,11 @@ impl Infra {
return Ok(());
}
tracing::info!(source, relay_count = relays.len(), "reconciling pending relay state");
tracing::info!(
source,
relay_count = relays.len(),
"reconciling pending relay state"
);
for relay in relays {
if relay.sync_error.trim().is_empty() {
+67
View File
@@ -1,5 +1,10 @@
use anyhow::{Result, anyhow};
use nostr_sdk::prelude::{Keys, nip44};
use serde::{Deserialize, Serialize};
const NIP44_ENVELOPE_PREFIX: &str = "enc:nip44:v2:";
const LEGACY_ENVELOPE_PREFIX: &str = "enc:v1:";
pub const RELAY_STATUS_ACTIVE: &str = "active";
pub const RELAY_STATUS_INACTIVE: &str = "inactive";
pub const RELAY_STATUS_DELINQUENT: &str = "delinquent";
@@ -36,6 +41,68 @@ pub struct Tenant {
pub past_due_at: Option<i64>,
}
impl Tenant {
pub fn encrypted_nwc_url_for_storage(&self) -> Result<String> {
Self::encrypt_nwc_url_for_storage(&self.nwc_url)
}
pub fn decrypt_nwc_url_from_storage(&mut self) -> Result<()> {
self.nwc_url = Self::decrypt_nwc_url_value_from_storage(&self.nwc_url)?;
Ok(())
}
fn encrypt_nwc_url_for_storage(value: &str) -> Result<String> {
if value.is_empty() {
return Ok(String::new());
}
let keys = Self::parse_nwc_url_cipher_keys()?;
let payload = nip44::encrypt(
keys.secret_key(),
&keys.public_key(),
value,
nip44::Version::V2,
)
.map_err(|e| anyhow!("failed to encrypt nwc_url with NIP-44: {e}"))?;
Ok(format!("{NIP44_ENVELOPE_PREFIX}{payload}"))
}
fn decrypt_nwc_url_value_from_storage(value: &str) -> Result<String> {
if value.is_empty() {
return Ok(String::new());
}
if value.starts_with(LEGACY_ENVELOPE_PREFIX) {
return Err(anyhow!(
"unsupported legacy encrypted nwc_url envelope; re-save tenant configuration"
));
}
let Some(payload) = value.strip_prefix(NIP44_ENVELOPE_PREFIX) else {
return Ok(value.to_string());
};
let keys = Self::parse_nwc_url_cipher_keys()?;
nip44::decrypt(keys.secret_key(), &keys.public_key(), payload)
.map_err(|e| anyhow!("failed to decrypt nwc_url with NIP-44: {e}"))
}
fn parse_nwc_url_cipher_keys() -> Result<Keys> {
let raw = std::env::var("NWC_URL_CIPHER_KEY")
.map_err(|_| anyhow!("missing NWC_URL_CIPHER_KEY environment variable"))?;
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err(anyhow!("missing NWC_URL_CIPHER_KEY environment variable"));
}
Keys::parse(trimmed).map_err(|e| {
anyhow!("NWC_URL_CIPHER_KEY must be a valid nostr secret key (hex or nsec): {e}")
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
pub struct Relay {
pub id: String,
+8 -3
View File
@@ -21,7 +21,7 @@ impl Query {
)
.fetch_all(&self.pool)
.await?;
Ok(rows)
rows.into_iter().map(decrypt_tenant_nwc_url).collect()
}
pub async fn get_tenant(&self, pubkey: &str) -> Result<Option<Tenant>> {
@@ -33,7 +33,7 @@ impl Query {
.bind(pubkey)
.fetch_optional(&self.pool)
.await?;
Ok(row)
row.map(decrypt_tenant_nwc_url).transpose()
}
pub fn list_plans() -> Vec<Plan> {
@@ -158,7 +158,7 @@ impl Query {
.bind(stripe_customer_id)
.fetch_optional(&self.pool)
.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>> {
@@ -224,3 +224,8 @@ impl Query {
Ok(found.is_some())
}
}
fn decrypt_tenant_nwc_url(mut tenant: Tenant) -> Result<Tenant> {
tenant.decrypt_nwc_url_from_storage()?;
Ok(tenant)
}
+1
View File
@@ -99,6 +99,7 @@ export type UpdateRelayInput = {
export type Tenant = {
pubkey: string
nwc_url: string
nwc_configured: boolean
created_at: number
stripe_customer_id: string
stripe_subscription_id: string | null
+1 -1
View File
@@ -135,7 +135,7 @@ export const reactivateRelayById = (id: string) => reactivateRelay(id)
export async function tenantNeedsPaymentSetup(): Promise<boolean> {
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> {
+3 -3
View File
@@ -18,9 +18,9 @@ export default function Account() {
const invoicesLoading = useMinLoading(() => invoices.loading)
const hasBillingChanges = createMemo(() => {
const current = tenant()?.nwc_url?.trim() ?? ""
const next = nwcUrl().trim()
return current !== next
if (next) return true
return tenant()?.nwc_configured ?? false
})
createEffect(() => {
@@ -169,7 +169,7 @@ export default function Account() {
<p class="text-xs text-gray-500 mt-0.5">{periodLabel()}</p>
</Show>
</div>
<div class="flex items-center gap-2 flex-shrink-0">
<div class="flex items-center gap-2 shrink-0">
<Show when={isOpen()}>
<span class="text-xs text-blue-600 font-medium">Pay now</span>
</Show>
+1 -1
View File
@@ -52,7 +52,7 @@ export default function RelayDetail() {
if (!isPaidRelay()) return false
const t = tenant()
if (!t) return false
return !t.nwc_url
return !t.nwc_configured
})
return (