forked from coracle/caravel
chore: encrypt tenant NWC URL at rest and stop secret exposure in tenant APIs
This commit is contained in:
@@ -28,5 +28,6 @@ LIVEKIT_API_SECRET=
|
||||
|
||||
# Billing
|
||||
NWC_URL= # Nostr Wallet Connect URL for generating Lightning invoices
|
||||
NWC_URL_CIPHER_KEY= # 32-byte hex/base64 key used to encrypt 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)
|
||||
|
||||
Generated
+1
@@ -203,6 +203,7 @@ dependencies = [
|
||||
"anyhow",
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"chacha20poly1305",
|
||||
"chrono",
|
||||
"dotenvy",
|
||||
"hex",
|
||||
|
||||
@@ -24,6 +24,7 @@ hmac = "0.12"
|
||||
sha2 = "0.10"
|
||||
dotenvy = "0.15.7"
|
||||
base64 = "0.22"
|
||||
chacha20poly1305 = { version = "0.10", features = ["std"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
|
||||
@@ -44,6 +44,7 @@ Environment variables:
|
||||
| `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` | 32-byte hex/base64 key used to encrypt 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_ |
|
||||
|
||||
+35
-6
@@ -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()
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ use tokio::sync::broadcast;
|
||||
use crate::models::{
|
||||
Activity, RELAY_STATUS_ACTIVE, RELAY_STATUS_DELINQUENT, RELAY_STATUS_INACTIVE, Relay, Tenant,
|
||||
};
|
||||
use crate::nwc_url_cipher;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Command {
|
||||
@@ -70,6 +71,7 @@ impl Command {
|
||||
anyhow::bail!("stripe_customer_id is required");
|
||||
}
|
||||
|
||||
let encrypted_nwc_url = nwc_url_cipher::encrypt_nwc_url(&tenant.nwc_url)?;
|
||||
let mut tx = self.pool.begin().await?;
|
||||
|
||||
sqlx::query(
|
||||
@@ -77,7 +79,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 +94,11 @@ impl Command {
|
||||
}
|
||||
|
||||
pub async fn update_tenant(&self, tenant: &Tenant) -> Result<()> {
|
||||
let encrypted_nwc_url = nwc_url_cipher::encrypt_nwc_url(&tenant.nwc_url)?;
|
||||
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?;
|
||||
|
||||
@@ -3,6 +3,7 @@ pub mod billing;
|
||||
pub mod command;
|
||||
pub mod infra;
|
||||
pub mod models;
|
||||
pub mod nwc_url_cipher;
|
||||
pub mod pool;
|
||||
pub mod query;
|
||||
pub mod robot;
|
||||
|
||||
@@ -3,6 +3,7 @@ mod billing;
|
||||
mod command;
|
||||
mod infra;
|
||||
mod models;
|
||||
mod nwc_url_cipher;
|
||||
mod pool;
|
||||
mod query;
|
||||
mod robot;
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
use anyhow::{Result, anyhow};
|
||||
use base64::Engine;
|
||||
use chacha20poly1305::aead::{Aead, KeyInit};
|
||||
use chacha20poly1305::{ChaCha20Poly1305, Nonce};
|
||||
use rand::RngCore;
|
||||
|
||||
const ENVELOPE_PREFIX: &str = "enc:v1:";
|
||||
const NONCE_LEN: usize = 12;
|
||||
const KEY_LEN: usize = 32;
|
||||
|
||||
pub fn is_encrypted_nwc_url(value: &str) -> bool {
|
||||
value.starts_with(ENVELOPE_PREFIX)
|
||||
}
|
||||
|
||||
pub fn encrypt_nwc_url(value: &str) -> Result<String> {
|
||||
if value.is_empty() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
|
||||
let key = parse_cipher_key()?;
|
||||
let cipher = ChaCha20Poly1305::new_from_slice(&key)
|
||||
.map_err(|e| anyhow!("invalid NWC_URL_CIPHER_KEY: {e}"))?;
|
||||
|
||||
let mut nonce = [0u8; NONCE_LEN];
|
||||
rand::rngs::OsRng.fill_bytes(&mut nonce);
|
||||
|
||||
let ciphertext = cipher
|
||||
.encrypt(Nonce::from_slice(&nonce), value.as_bytes())
|
||||
.map_err(|e| anyhow!("failed to encrypt nwc_url: {e}"))?;
|
||||
|
||||
let nonce_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(nonce);
|
||||
let ciphertext_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(ciphertext);
|
||||
|
||||
Ok(format!("{ENVELOPE_PREFIX}{nonce_b64}:{ciphertext_b64}"))
|
||||
}
|
||||
|
||||
pub fn decrypt_nwc_url(value: &str) -> Result<String> {
|
||||
if value.is_empty() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
|
||||
if !is_encrypted_nwc_url(value) {
|
||||
return Ok(value.to_string());
|
||||
}
|
||||
|
||||
let payload = value
|
||||
.strip_prefix(ENVELOPE_PREFIX)
|
||||
.ok_or_else(|| anyhow!("invalid encrypted nwc_url envelope"))?;
|
||||
let (nonce_b64, ciphertext_b64) = payload
|
||||
.split_once(':')
|
||||
.ok_or_else(|| anyhow!("invalid encrypted nwc_url envelope"))?;
|
||||
|
||||
let nonce_raw = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(nonce_b64)
|
||||
.map_err(|e| anyhow!("invalid encrypted nwc_url nonce: {e}"))?;
|
||||
let nonce: [u8; NONCE_LEN] = nonce_raw
|
||||
.try_into()
|
||||
.map_err(|_| anyhow!("invalid encrypted nwc_url nonce length"))?;
|
||||
|
||||
let ciphertext = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(ciphertext_b64)
|
||||
.map_err(|e| anyhow!("invalid encrypted nwc_url ciphertext: {e}"))?;
|
||||
|
||||
let key = parse_cipher_key()?;
|
||||
let cipher = ChaCha20Poly1305::new_from_slice(&key)
|
||||
.map_err(|e| anyhow!("invalid NWC_URL_CIPHER_KEY: {e}"))?;
|
||||
|
||||
let plaintext = cipher
|
||||
.decrypt(Nonce::from_slice(&nonce), ciphertext.as_ref())
|
||||
.map_err(|e| anyhow!("failed to decrypt nwc_url: {e}"))?;
|
||||
|
||||
String::from_utf8(plaintext).map_err(|e| anyhow!("decrypted nwc_url is not utf-8: {e}"))
|
||||
}
|
||||
|
||||
fn parse_cipher_key() -> Result<[u8; KEY_LEN]> {
|
||||
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"));
|
||||
}
|
||||
|
||||
let key_bytes = if let Ok(decoded_hex) = hex::decode(trimmed) {
|
||||
if decoded_hex.len() == KEY_LEN {
|
||||
decoded_hex
|
||||
} else {
|
||||
decode_base64_key(trimmed)?
|
||||
}
|
||||
} else {
|
||||
decode_base64_key(trimmed)?
|
||||
};
|
||||
|
||||
if key_bytes.len() != KEY_LEN {
|
||||
return Err(anyhow!(
|
||||
"NWC_URL_CIPHER_KEY must decode to exactly {KEY_LEN} bytes"
|
||||
));
|
||||
}
|
||||
|
||||
let mut key = [0u8; KEY_LEN];
|
||||
key.copy_from_slice(&key_bytes);
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
fn decode_base64_key(value: &str) -> Result<Vec<u8>> {
|
||||
base64::engine::general_purpose::STANDARD
|
||||
.decode(value)
|
||||
.or_else(|_| base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(value))
|
||||
.map_err(|e| anyhow!("NWC_URL_CIPHER_KEY must be 32-byte hex or base64: {e}"))
|
||||
}
|
||||
@@ -7,6 +7,8 @@ use sqlx::{
|
||||
sqlite::{SqliteConnectOptions, SqlitePoolOptions},
|
||||
};
|
||||
|
||||
use crate::nwc_url_cipher;
|
||||
|
||||
pub async fn create_pool() -> Result<SqlitePool> {
|
||||
let raw_database_url = std::env::var("DATABASE_URL")
|
||||
.unwrap_or_else(|_| format!("sqlite://{}/data/caravel.db", env!("CARGO_MANIFEST_DIR")));
|
||||
@@ -33,10 +35,34 @@ pub async fn create_pool() -> Result<SqlitePool> {
|
||||
.await?;
|
||||
|
||||
sqlx::migrate!("./migrations").run(&pool).await?;
|
||||
migrate_legacy_tenant_nwc_urls(&pool).await?;
|
||||
|
||||
Ok(pool)
|
||||
}
|
||||
|
||||
async fn migrate_legacy_tenant_nwc_urls(pool: &SqlitePool) -> Result<()> {
|
||||
let rows = sqlx::query_as::<_, (String, String)>(
|
||||
"SELECT pubkey, nwc_url FROM tenant WHERE nwc_url != ''",
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
|
||||
for (pubkey, nwc_url) in rows {
|
||||
if nwc_url_cipher::is_encrypted_nwc_url(&nwc_url) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let encrypted_nwc_url = nwc_url_cipher::encrypt_nwc_url(&nwc_url)?;
|
||||
sqlx::query("UPDATE tenant SET nwc_url = ? WHERE pubkey = ?")
|
||||
.bind(encrypted_nwc_url)
|
||||
.bind(pubkey)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn normalize_sqlite_url(url: &str) -> String {
|
||||
let Some(path) = url.strip_prefix("sqlite://") else {
|
||||
return url.to_string();
|
||||
|
||||
@@ -2,6 +2,7 @@ use anyhow::Result;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
use crate::models::{Activity, Plan, Relay, Tenant};
|
||||
use crate::nwc_url_cipher;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Query {
|
||||
@@ -21,7 +22,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 +34,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 +159,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 +225,8 @@ impl Query {
|
||||
Ok(found.is_some())
|
||||
}
|
||||
}
|
||||
|
||||
fn decrypt_tenant_nwc_url(mut tenant: Tenant) -> Result<Tenant> {
|
||||
tenant.nwc_url = nwc_url_cipher::decrypt_nwc_url(&tenant.nwc_url)?;
|
||||
Ok(tenant)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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 (
|
||||
|
||||
Reference in New Issue
Block a user