Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix: prevent duplicate stripe subscriptions (#1268)
Will Hutchinson525e015952d0
diff --git a/js/app/packages/service-clients/service-auth/generated/client.ts b/js/app/packages/service-clients/service-auth/generated/client.tsindex f9a80bb0c8..7cbe9c4eac 100644--- a/js/app/packages/service-clients/service-auth/generated/client.ts+++ b/js/app/packages/service-clients/service-auth/generated/client.ts@@ -3064,6 +3064,11 @@ export type createCheckoutSessionResponse404 = {status: 404;};+export type createCheckoutSessionResponse409 = {+ data: string;+ status: 409;+};+export type createCheckoutSessionResponse500 = {data: string;status: 500;@@ -3076,6 +3081,7 @@ export type createCheckoutSessionResponseSuccess =export type createCheckoutSessionResponseError = (| createCheckoutSessionResponse400| createCheckoutSessionResponse404+ | createCheckoutSessionResponse409| createCheckoutSessionResponse500) & {headers: Headers;diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.jsonindex 230168588d..555d1de184 100644--- a/js/app/packages/service-clients/service-auth/openapi.json+++ b/js/app/packages/service-clients/service-auth/openapi.json@@ -2681,6 +2681,16 @@}}},+ "409": {+ "description": "",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },"500": {"description": "","content": {diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe.rsindex ac005668c4..0754e26ff9 100644--- a/rust/cloud-storage/authentication_service/src/api/user/stripe.rs+++ b/rust/cloud-storage/authentication_service/src/api/user/stripe.rs@@ -32,6 +32,8 @@ pub enum StripeOperationError {PromoCodeNotFound,#[error("Internal server error")]UnexpectedStripeResponse,+ #[error("User already has an active subscription")]+ AlreadySubscribed,}impl IntoResponse for StripeOperationError {@@ -44,6 +46,7 @@ impl IntoResponse for StripeOperationError {StripeOperationError::StripeErr(_) => StatusCode::INTERNAL_SERVER_ERROR,StripeOperationError::PromoCodeNotFound => StatusCode::NOT_FOUND,StripeOperationError::UnexpectedStripeResponse => StatusCode::INTERNAL_SERVER_ERROR,+ StripeOperationError::AlreadySubscribed => StatusCode::CONFLICT,};(status, self.to_string()).into_response()}@@ -99,6 +102,7 @@ pub struct CreatePortalSessionRequest {(status = 200, body = StripeSessionResponse),(status = 400, body = String),(status = 404, body = String),+ (status = 409, body = String),(status = 500, body = String),))]@@ -119,6 +123,28 @@ pub async fn create_checkout_session(let customer_id: stripe::CustomerId = stripe_customer_id.parse()?;+ // Check if user already has an active subscription+ let mut list_subscriptions = stripe::ListSubscriptions::new();+ list_subscriptions.customer = Some(customer_id.clone());+ list_subscriptions.limit = Some(10);++ let subscriptions = stripe::Subscription::list(&ctx.stripe_client, &list_subscriptions).await?;++ let has_active_subscription = subscriptions.data.iter().any(|sub| {+ matches!(+ sub.status,+ stripe::SubscriptionStatus::Active | stripe::SubscriptionStatus::Trialing+ )+ });++ if has_active_subscription {+ tracing::warn!(+ customer_id = %customer_id,+ "User attempted to create checkout session but already has an active subscription"+ );+ return Err(StripeOperationError::AlreadySubscribed);+ }+// If a discount code is provided, look up the promotion code IDlet promo_code_id = if let Some(ref discount) = req.discount {let mut list_params = stripe::ListPromotionCodes::new();diff --git a/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rs b/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rsindex 267213be18..1d5f265f7e 100644--- a/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rs+++ b/rust/cloud-storage/authentication_service/src/api/webhooks/user/stripe_webhook.rs@@ -149,6 +149,69 @@ async fn handle_customer_subscription_event(.await;}+ // Check for duplicate subscriptions+ let mut list_subscriptions = stripe::ListSubscriptions::new();+ list_subscriptions.customer = Some(customer_id.clone());+ list_subscriptions.limit = Some(10);++ let all_subscriptions =+ stripe::Subscription::list(&ctx.stripe_client, &list_subscriptions).await?;++ let active_subscriptions: Vec<_> = all_subscriptions+ .data+ .iter()+ .filter(|sub| {+ matches!(+ sub.status,+ stripe::SubscriptionStatus::Active | stripe::SubscriptionStatus::Trialing+ )+ })+ .collect();++ // If this is a new active/trialing subscription and there are multiple active subscriptions,+ // cancel the newer one (keep the oldest)+ if matches!(subscription_status, "active" | "trialing") && active_subscriptions.len() > 1 {+ // Find the oldest subscription by created timestamp+ let oldest_subscription = active_subscriptions+ .iter()+ .min_by_key(|sub| sub.created)+ .map(|sub| sub.id.as_str());++ // If the current subscription is not the oldest, cancel it+ if oldest_subscription != Some(subscription_id) {+ tracing::warn!(+ customer_id = %customer_id,+ subscription_id = subscription_id,+ oldest_subscription_id = ?oldest_subscription,+ total_active = active_subscriptions.len(),+ "Cancelling duplicate subscription - keeping oldest"+ );++ let sub_id: stripe::SubscriptionId = subscription_id.parse()?;+ stripe::Subscription::cancel(+ &ctx.stripe_client,+ &sub_id,+ stripe::CancelSubscription::default(),+ )+ .await?;++ // Return early - don't update permissions for a cancelled duplicate+ return Ok(());+ }+ }++ // If subscription is being deleted/canceled, check if there's another active subscription+ // before revoking permissions+ if subscription_status == "canceled" && !active_subscriptions.is_empty() {+ tracing::info!(+ customer_id = %customer_id,+ subscription_id = subscription_id,+ remaining_active = active_subscriptions.len(),+ "Subscription deleted but user still has active subscription(s) - not revoking permissions"+ );+ return Ok(());+ }+if subscription_status == "trialing" {// Add has_trialed: true to stripe customer metadatalet mut params = stripe::UpdateCustomer::new();