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
chore(stripe): remove legacy stripe subscription code (#3790)
Will Hutchinsonc2904424db21
diff --git a/infra/stacks/authentication-service/Pulumi.dev.yaml b/infra/stacks/authentication-service/Pulumi.dev.yamlindex 898a137a3d..94de172dc9 100644--- a/infra/stacks/authentication-service/Pulumi.dev.yaml+++ b/infra/stacks/authentication-service/Pulumi.dev.yaml@@ -26,6 +26,3 @@ config:authentication-service:meta_access_token: meta-access-tokenauthentication-service:posthog_host: https://us.i.posthog.comauthentication-service:posthog_api_key: posthog-api-key- authentication-service:stripe_price_id_haiku: stripe-price-id-haiku-dev- authentication-service:stripe_price_id_sonnet: stripe-price-id-sonnet-dev- authentication-service:stripe_price_id_opus: stripe-price-id-opus-devdiff --git a/infra/stacks/authentication-service/Pulumi.prod.yaml b/infra/stacks/authentication-service/Pulumi.prod.yamlindex 14628539fa..8d314fd194 100644--- a/infra/stacks/authentication-service/Pulumi.prod.yaml+++ b/infra/stacks/authentication-service/Pulumi.prod.yaml@@ -26,6 +26,3 @@ config:authentication-service:meta_access_token: meta-access-tokenauthentication-service:posthog_host: https://us.i.posthog.comauthentication-service:posthog_api_key: posthog-api-key- authentication-service:stripe_price_id_haiku: stripe-price-id-haiku-prod- authentication-service:stripe_price_id_sonnet: stripe-price-id-sonnet-prod- authentication-service:stripe_price_id_opus: stripe-price-id-opus-proddiff --git a/infra/stacks/authentication-service/index.ts b/infra/stacks/authentication-service/index.tsindex 7cf222ac37..ee0ac71544 100644--- a/infra/stacks/authentication-service/index.ts+++ b/infra/stacks/authentication-service/index.ts@@ -119,21 +119,6 @@ const googleClientSecretKeyArn: pulumi.Output<string> = aws.secretsmanager.getSecretVersionOutput({ secretId: GOOGLE_CLIENT_SECRET_KEY }).apply((secret) => secret.arn);-// -- STRIPE PRICE IDs-const STRIPE_PRICE_ID_HAIKU = aws.secretsmanager- .getSecretVersionOutput({ secretId: config.require('stripe_price_id_haiku') })- .apply((s) => s.secretString);--const STRIPE_PRICE_ID_SONNET = aws.secretsmanager- .getSecretVersionOutput({- secretId: config.require('stripe_price_id_sonnet'),- })- .apply((s) => s.secretString);--const STRIPE_PRICE_ID_OPUS = aws.secretsmanager- .getSecretVersionOutput({ secretId: config.require('stripe_price_id_opus') })- .apply((s) => s.secretString);-const MACRO_API_TOKEN_EXPIRY_SECONDS = config.require(`macro_api_token_expiry_seconds`);@@ -345,19 +330,6 @@ const service = new AuthenticationService('authentication-service', {name: 'STRIPE_WEBHOOK_SECRET_KEY',value: pulumi.interpolate`${stripeWebhookSecretKeyArn}`,},- // Stripe price ids- {- name: 'STRIPE_PRICE_ID_HAIKU',- value: pulumi.interpolate`${STRIPE_PRICE_ID_HAIKU}`,- },- {- name: 'STRIPE_PRICE_ID_SONNET',- value: pulumi.interpolate`${STRIPE_PRICE_ID_SONNET}`,- },- {- name: 'STRIPE_PRICE_ID_OPUS',- value: pulumi.interpolate`${STRIPE_PRICE_ID_OPUS}`,- },// Github{name: 'GITHUB_CLIENT_ID',diff --git a/js/app/packages/app/component/paywall/PaywallComponent.tsx b/js/app/packages/app/component/paywall/PaywallComponent.tsxindex e85e6a6b4c..56d1b69b0e 100644--- a/js/app/packages/app/component/paywall/PaywallComponent.tsx+++ b/js/app/packages/app/component/paywall/PaywallComponent.tsx@@ -1,7 +1,4 @@-import { ShowFeatureFlag } from '@app/lib/analytics/posthog';-import { ENABLE_NEW_PRICING_OVERRIDE } from '@core/constant/featureFlags';import type { PaywallKey } from '@core/constant/PaywallState';-import PaywallComponentLegacy from './PaywallComponentLegacy';import PaywallComponentNew from './PaywallComponentNew';export interface PaywallProps {@@ -14,13 +11,7 @@ export interface PaywallProps {}const PaywallComponent = (props: PaywallProps) => (- <ShowFeatureFlag- key="enable-new-pricing"- enabledOverride={ENABLE_NEW_PRICING_OVERRIDE}- fallback={<PaywallComponentLegacy {...props} />}- >- <PaywallComponentNew {...props} />- </ShowFeatureFlag>+ <PaywallComponentNew {...props} />);export default PaywallComponent;diff --git a/js/app/packages/app/component/paywall/PaywallComponentLegacy.tsx b/js/app/packages/app/component/paywall/PaywallComponentLegacy.tsxdeleted file mode 100644index c66cdc8d69..0000000000--- a/js/app/packages/app/component/paywall/PaywallComponentLegacy.tsx+++ /dev/null@@ -1,244 +0,0 @@-import { useAnalytics } from '@app/component/analytics-context';-import { useHasPaidAccess } from '@core/auth';-import { toast } from '@core/component/Toast/Toast';-import { type PaywallKey, PaywallMessages } from '@core/constant/PaywallState';-import { usePermissions } from '@core/context/user';-import IconX from '@phosphor/x.svg';-import { invalidateUserInfo } from '@queries/auth/user-info';-import type { StripeProductTier } from '@service-auth/generated/schemas/stripeProductTier';-import { stripeServiceClient } from '@service-stripe/client';-import { Button, cn } from '@ui';-import { createMemo, createSignal, For, Show } from 'solid-js';-import { match } from 'ts-pattern';-import type { PaywallProps } from './PaywallComponent';-import { LEGACY_PLANS, type PaidPlanTier, PLAN_FEATURES } from './plans';-import SubscriptionTier from './SubscriptionTier';--type LegacyPaidPlan = Exclude<(typeof LEGACY_PLANS)[number], { tier: 'free' }>;--// Paid-only plans for the billing paywall — Stripe has no product for the-// 'free' tier, so it must be excluded here.-const PaywallComponentLegacy = (props: PaywallProps) => {- const paidPlans = LEGACY_PLANS.filter(- (p): p is LegacyPaidPlan => p.tier !== 'free'- );-- const analytics = useAnalytics();- const permissions = usePermissions();- const hasPaid = useHasPaidAccess();-- // Tier a paying user is currently subscribed to, derived from RBAC permissions- // (sub_opus grants write:opus; sub_sonnet grants write:sonnet + write:haiku;- // sub_haiku grants write:haiku — so check highest-to-lowest).- const currentTier = createMemo((): PaidPlanTier | undefined => {- if (!hasPaid()) return undefined;- const perms = permissions();- if (perms.includes('write:opus')) return 'opus';- if (perms.includes('write:sonnet')) return 'sonnet';- if (perms.includes('write:haiku')) return 'haiku';- return undefined;- });-- const [userSelectedTier, setUserSelectedTier] =- createSignal<PaidPlanTier | null>(null);- const selectedTier = createMemo<PaidPlanTier>(- () => userSelectedTier() ?? currentTier() ?? 'sonnet'- );-- const [updating, setUpdating] = createSignal(false);-- const handleCheckout = async (tier: PaidPlanTier) => {- try {- await props.cb();- const url = await stripeServiceClient.createCheckoutSession({- type: props.customType- ? props.customType- : (props.errorKey ?? undefined),- tier: tier as StripeProductTier,- });- analytics.track('subscription_start', {- type: tier,- customType: props.customType,- errorKey: props.errorKey,- });- window.location.href = url;- } catch (error) {- console.error(error);- }- };-- const manageSubscription = async () => {- try {- const url = await stripeServiceClient.createPortalSession();- window.location.href = url;- } catch (error) {- console.error(error);- }- };-- const handleContinue = () => {- if (hasPaid()) {- manageSubscription();- return;- }- handleCheckout(selectedTier());- };-- const handleUpdateTier = async () => {- const next = selectedTier();- const prev = currentTier();- if (!prev || next === prev) return;- setUpdating(true);- try {- const result = await stripeServiceClient.updateSubscriptionTier(- next as StripeProductTier- );- if (!result.ok) {- const message = match(result.code)- .with('USER_IN_TEAM', () => 'Contact your team owner to update.')- .with(- 'UPDATE_IN_PROGRESS',- () =>- 'Another subscription update is already in progress. Please try again in a moment.'- )- .with(- 'NO_SUBSCRIPTION',- () => "You don't have an active subscription to update."- )- .with(- 'TIER_UNCHANGED',- () => 'Subscription is already on the requested tier.'- )- .with('UNKNOWN', () => 'Failed to update subscription.')- .exhaustive();- toast.failure(message);- return;- }- analytics.track('subscription_tier_updated', { from: prev, to: next });- await invalidateUserInfo();- toast.success('Subscription updated!');- } finally {- setUpdating(false);- }- };-- return (- <div class="relative space-y-2 w-full">- <Show when={!props.hideCloseButton}>- <button- onClick={props.cb}- class="absolute -top-2 -right-2 sm:-top-3 sm:-right-3 text-ink-extra-muted hover:text-ink transition-colors z-10"- >- <IconX class="size-5 sm:size-6" />- </button>- </Show>- <Show when={!hasPaid()}>- <div class="relative w-full text-center">- <div class="space-y-6 sm:space-y-8">- <div class="text-center">- <h2 class="mb-2 font-semibold text-ink text-xl sm:text-2xl">- Choose your plan- </h2>- <Show when={props.errorKey}>- <p class="mb-4 text-failure-ink text-sm sm:text-base">- {PaywallMessages[props.errorKey as PaywallKey]}- </p>- </Show>- </div>- </div>- </div>- </Show>-- <div class="w-full @container">- <div class="gap-2 grid grid-cols-1 @[530px]:grid-cols-3">- <For each={paidPlans}>- {(plan) => (- <button- onClick={() => setUserSelectedTier(plan.tier)}- class={cn(- selectedTier() === plan.tier- ? 'border-accent bg-active'- : 'border-edge hover:border-edge',- 'p-4 sm:p-5 border flex flex-col transition-all relative text-left rounded-sm'- )}- >- <div class="flex flex-col gap-3 w-full">- <div class="flex justify-between items-start">- <div>- <div class="font-semibold text-ink text-base sm:text-lg">- {plan.name}- </div>- </div>- <SubscriptionTier- class="w-7 shrink-0"- tier={- selectedTier() === plan.tier ? plan.tier : undefined- }- />- </div>- <div class="flex items-baseline gap-0.5">- <span class="text-3xl font-bold text-ink">- ${plan.price}- </span>- <span class="text-base text-ink/40">/mo</span>- </div>- <div class="text-sm text-ink/60 flex flex-col gap-1">- <For each={PLAN_FEATURES}>- {(feature) => (- <span>- {feature.label}: {feature.values[plan.tier]}- </span>- )}- </For>- </div>- </div>- </button>- )}- </For>- </div>- </div>-- <div class="w-full">- <Show- when={hasPaid() && currentTier() && selectedTier() !== currentTier()}- fallback={- <Button- onClick={handleContinue}- variant="base"- size="lg"- depth={3}- class="w-full"- >- <Show when={!hasPaid()} fallback={'Manage Subscription'}>- Get {LEGACY_PLANS.find((p) => p.tier === selectedTier())?.name}- </Show>- </Button>- }- >- <Button- onClick={handleUpdateTier}- disabled={updating()}- variant="active"- size="lg"- depth={3}- class="w-full"- >- {updating() ? 'Updating…' : 'Update Subscription'}- </Button>- </Show>- <Show when={!hasPaid() && props.handleGuest}>- <Button- onClick={() => props.handleGuest?.()}- variant="base"- size="sm"- class="mt-3 text-ink/40 hover:text-ink/60"- >- Continue with free plan- </Button>- </Show>- </div>- </div>- );-};--export default PaywallComponentLegacy;diff --git a/js/app/packages/service-clients/service-auth/client.ts b/js/app/packages/service-clients/service-auth/client.tsindex 1a612240d4..6bc8e00574 100644--- a/js/app/packages/service-clients/service-auth/client.ts+++ b/js/app/packages/service-clients/service-auth/client.ts@@ -20,7 +20,6 @@ import type {GmailLinkStatusResponse,InitGithubLinkResponse,InitGmailLinkResponse,- PatchSubscriptionTierRequest,PatchUserTutorialRequest,SendMobileWelcomeEmailResponse,UserQuota,@@ -137,12 +136,6 @@ async function getAccessToken(): Promise<string | null> {return accessToken;}-export type PatchSubscriptionTierErrorCode =- | 'TIER_UNCHANGED'- | 'USER_IN_TEAM'- | 'NO_SUBSCRIPTION'- | 'UPDATE_IN_PROGRESS';-export type GithubReauthenticationErrorCode = 'REAUTHENTICATION_REQUIRED';const githubErrorResponseHandler: ErrorResponseHandler<GithubReauthenticationErrorCode> =@@ -523,65 +516,6 @@ export const authServiceClient = {).map((result) => result.url);},- /**- * Patches the current user's subscription tier. Backend swaps both the RBAC role and- * Stripe subscription line item; caller should invalidate user info afterwards so the- * new permissions are picked up.- *- * Maps each distinct backend failure (distinguished by HTTP status) to a semantic code- * the UI can switch on. Uses `_fetchWithAuth` directly so the `CustomErrorCode` generic- * survives the module-level `fetchWithAuth` cast.- */- async patchSubscriptionTier(args: PatchSubscriptionTierRequest) {- return _fetchWithAuth<{}, PatchSubscriptionTierErrorCode>(- `${authHost}/user/stripe/subscription`,- {- method: 'PATCH',- body: JSON.stringify(args),- errorResponseHandler: async (response) => {- // Custom handler fully replaces fetchWithAuth's default mapping, so preserve- // the base cases we still want (401/500) alongside our endpoint-specific codes.- switch (response.status) {- case 400:- return {- code: 'TIER_UNCHANGED',- message: 'Subscription is already on the requested tier',- };- case 401:- return { code: 'UNAUTHORIZED', message: 'Unauthorized access' };- case 403:- return {- code: 'USER_IN_TEAM',- message:- 'User is a member of a team; tier is managed by the team owner',- };- case 404:- return {- code: 'NO_SUBSCRIPTION',- message: 'User does not have an active subscription',- };- case 409:- return {- code: 'UPDATE_IN_PROGRESS',- message:- 'Another subscription update is already in progress for this user',- };- case 500:- return {- code: 'SERVER_ERROR',- message: 'Internal server error',- };- default:- return {- code: 'HTTP_ERROR',- message: `HTTP error! status: ${response.status}`,- };- }- },- }- );- },-async checkGithubLinkStatus() {return (await fetchWithAuth<diff --git a/js/app/packages/service-clients/service-auth/generated/client.ts b/js/app/packages/service-clients/service-auth/generated/client.tsindex 3aa9041d58..25c890d5e2 100644--- a/js/app/packages/service-clients/service-auth/generated/client.ts+++ b/js/app/packages/service-clients/service-auth/generated/client.ts@@ -7,7 +7,6 @@import type {AppleLoginRequest,CreateAccountMergeRequest,- CreateCheckoutSessionRequest,CreateCheckoutSessionV2Request,CreateInProgressLinkResponse,CreatePortalSessionRequest,@@ -36,7 +35,6 @@ import type {PasswordlessCallbackParams,PasswordlessRequest,PasswordRequest,- PatchSubscriptionTierRequest,PatchTeamCrmSettingsRequest,PatchTeamCrmSettingsResponse,PatchTeamRequest,@@ -3740,78 +3738,6 @@ export const getUserQuota = async (} as getUserQuotaResponse;};-/**- * @summary **LEGACY DO NOT USE** Creates a Stripe checkout session for the user to subscribe.- */-export type createCheckoutSessionResponse200 = {- data: StripeSessionResponse;- status: 200;-};--export type createCheckoutSessionResponse400 = {- data: ErrorResponse;- status: 400;-};--export type createCheckoutSessionResponse404 = {- data: ErrorResponse;- status: 404;-};--export type createCheckoutSessionResponse409 = {- data: ErrorResponse;- status: 409;-};--export type createCheckoutSessionResponse500 = {- data: ErrorResponse;- status: 500;-};--export type createCheckoutSessionResponseSuccess =- createCheckoutSessionResponse200 & {- headers: Headers;- };-export type createCheckoutSessionResponseError = (- | createCheckoutSessionResponse400- | createCheckoutSessionResponse404- | createCheckoutSessionResponse409- | createCheckoutSessionResponse500-) & {- headers: Headers;-};--export type createCheckoutSessionResponse =- | createCheckoutSessionResponseSuccess- | createCheckoutSessionResponseError;--export const getCreateCheckoutSessionUrl = () => {- return `/user/stripe/checkout`;-};--export const createCheckoutSession = async (- createCheckoutSessionRequest: CreateCheckoutSessionRequest,- options?: RequestInit-): Promise<createCheckoutSessionResponse> => {- const res = await fetch(getCreateCheckoutSessionUrl(), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(createCheckoutSessionRequest),- });-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: createCheckoutSessionResponse['data'] = body- ? JSON.parse(body)- : {};- return {- data,- status: res.status,- headers: res.headers,- } as createCheckoutSessionResponse;-};-/*** @summary Creates a Stripe checkout session for the user to subscribe.*/@@ -3944,84 +3870,6 @@ export const createPortalSession = async (} as createPortalSessionResponse;};-/**- * @summary Updates the user's subscription tier, swapping both their RBAC role and Stripe subscription line item.- */-export type patchSubscriptionTierResponse200 = {- data: void;- status: 200;-};--export type patchSubscriptionTierResponse400 = {- data: ErrorResponse;- status: 400;-};--export type patchSubscriptionTierResponse403 = {- data: ErrorResponse;- status: 403;-};--export type patchSubscriptionTierResponse404 = {- data: ErrorResponse;- status: 404;-};--export type patchSubscriptionTierResponse409 = {- data: ErrorResponse;- status: 409;-};--export type patchSubscriptionTierResponse500 = {- data: ErrorResponse;- status: 500;-};--export type patchSubscriptionTierResponseSuccess =- patchSubscriptionTierResponse200 & {- headers: Headers;- };-export type patchSubscriptionTierResponseError = (- | patchSubscriptionTierResponse400- | patchSubscriptionTierResponse403- | patchSubscriptionTierResponse404- | patchSubscriptionTierResponse409- | patchSubscriptionTierResponse500-) & {- headers: Headers;-};--export type patchSubscriptionTierResponse =- | patchSubscriptionTierResponseSuccess- | patchSubscriptionTierResponseError;--export const getPatchSubscriptionTierUrl = () => {- return `/user/stripe/subscription`;-};--export const patchSubscriptionTier = async (- patchSubscriptionTierRequest: PatchSubscriptionTierRequest,- options?: RequestInit-): Promise<patchSubscriptionTierResponse> => {- const res = await fetch(getPatchSubscriptionTierUrl(), {- ...options,- method: 'PATCH',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(patchSubscriptionTierRequest),- });-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: patchSubscriptionTierResponse['data'] = body- ? JSON.parse(body)- : {};- return {- data,- status: res.status,- headers: res.headers,- } as patchSubscriptionTierResponse;-};-/*** @summary Updates the user's tutorialComplete flag.*/diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionRequest.tsdeleted file mode 100644index a9669c6d8f..0000000000--- a/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionRequest.ts+++ /dev/null@@ -1,26 +0,0 @@-/**- * Generated by orval v7.21.0 🍺- * Do not edit manually.- * authentication_service- * OpenAPI spec version: 0.1.0- */--import type { CheckoutSessionMetadata } from './checkoutSessionMetadata';-import type { CreateCheckoutSessionRequestDiscount } from './createCheckoutSessionRequestDiscount';-import type { StripeProductTier } from './stripeProductTier';--/**- * Request body for creating a Stripe checkout session- */-export interface CreateCheckoutSessionRequest {- /** The URL to redirect to if checkout is cancelled */- cancelUrl: string;- /** Optional discount/promo code to apply */- discount?: CreateCheckoutSessionRequestDiscount;- /** Tracking metadata for conversion attribution */- metadata?: CheckoutSessionMetadata;- /** The URL to redirect to on successful checkout */- successUrl: string;- /** The tier, defaults to haiku */- tier?: StripeProductTier;-}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionRequestDiscount.ts b/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionRequestDiscount.tsdeleted file mode 100644index a59c575391..0000000000--- a/js/app/packages/service-clients/service-auth/generated/schemas/createCheckoutSessionRequestDiscount.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.21.0 🍺- * Do not edit manually.- * authentication_service- * OpenAPI spec version: 0.1.0- */--/**- * Optional discount/promo code to apply- */-export type CreateCheckoutSessionRequestDiscount = string | null;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts b/js/app/packages/service-clients/service-auth/generated/schemas/index.tsindex 5495b47d00..61c94e88f7 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts@@ -12,8 +12,6 @@ export * from './checkoutSessionMetadataFbc';export * from './checkoutSessionMetadataFbp';export * from './checkoutSessionMetadataGaClientId';export * from './createAccountMergeRequest';-export * from './createCheckoutSessionRequest';-export * from './createCheckoutSessionRequestDiscount';export * from './createCheckoutSessionV2Request';export * from './createCheckoutSessionV2RequestDiscount';export * from './createInProgressLinkResponse';@@ -68,7 +66,6 @@ export * from './passwordlessCallbackParams';export * from './passwordlessRequest';export * from './passwordlessRequestReferralCode';export * from './passwordRequest';-export * from './patchSubscriptionTierRequest';export * from './patchTeamCrmSettingsRequest';export * from './patchTeamCrmSettingsResponse';export * from './patchTeamRequest';@@ -94,7 +91,6 @@ export * from './sendMobileWelcomeEmailRequest';export * from './sendMobileWelcomeEmailResponse';export * from './ssoLoginParams';export * from './ssoRequiredResponse';-export * from './stripeProductTier';export * from './stripeSessionResponse';export * from './team';export * from './teamInviteDetails';diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/patchSubscriptionTierRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/patchSubscriptionTierRequest.tsdeleted file mode 100644index e56be31bc3..0000000000--- a/js/app/packages/service-clients/service-auth/generated/schemas/patchSubscriptionTierRequest.ts+++ /dev/null@@ -1,15 +0,0 @@-/**- * Generated by orval v7.21.0 🍺- * Do not edit manually.- * authentication_service- * OpenAPI spec version: 0.1.0- */-import type { StripeProductTier } from './stripeProductTier';--/**- * Request body for changing the user's subscription tier- */-export interface PatchSubscriptionTierRequest {- /** The new tier to move the user to */- newTier: StripeProductTier;-}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/stripeProductTier.ts b/js/app/packages/service-clients/service-auth/generated/schemas/stripeProductTier.tsdeleted file mode 100644index fac40b1c2f..0000000000--- a/js/app/packages/service-clients/service-auth/generated/schemas/stripeProductTier.ts+++ /dev/null@@ -1,16 +0,0 @@-/**- * Generated by orval v7.21.0 🍺- * Do not edit manually.- * authentication_service- * OpenAPI spec version: 0.1.0- */--export type StripeProductTier =- (typeof StripeProductTier)[keyof typeof StripeProductTier];--// eslint-disable-next-line @typescript-eslint/no-redeclare-export const StripeProductTier = {- haiku: 'haiku',- sonnet: 'sonnet',- opus: 'opus',-} as const;diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.jsonindex eaaff9f661..b58372890a 100644--- a/js/app/packages/service-clients/service-auth/openapi.json+++ b/js/app/packages/service-clients/service-auth/openapi.json@@ -3112,75 +3112,6 @@}}},- "/user/stripe/checkout": {- "post": {- "tags": ["user::stripe::create_checkout_session"],- "summary": "**LEGACY DO NOT USE** Creates a Stripe checkout session for the user to subscribe.",- "operationId": "create_checkout_session",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/CreateCheckoutSessionRequest"- }- }- },- "required": true- },- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/StripeSessionResponse"- }- }- }- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "404": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "409": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- }- }- }- },"/user/stripe/checkoutv2": {"post": {"tags": ["user::stripe::create_checkout_session_v2"],@@ -3299,78 +3230,6 @@}}},- "/user/stripe/subscription": {- "patch": {- "tags": ["user::stripe::patch_subscription_tier"],- "summary": "Updates the user's subscription tier, swapping both their RBAC role and Stripe subscription line item.",- "operationId": "patch_subscription_tier",- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/PatchSubscriptionTierRequest"- }- }- },- "required": true- },- "responses": {- "200": {- "description": ""- },- "400": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "403": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "404": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "409": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- },- "500": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ErrorResponse"- }- }- }- }- }- }- },"/user/tutorial": {"patch": {"tags": ["user::patch_tutorial"],@@ -3477,33 +3336,6 @@}}},- "CreateCheckoutSessionRequest": {- "type": "object",- "description": "Request body for creating a Stripe checkout session",- "required": ["successUrl", "cancelUrl"],- "properties": {- "cancelUrl": {- "type": "string",- "description": "The URL to redirect to if checkout is cancelled"- },- "discount": {- "type": ["string", "null"],- "description": "Optional discount/promo code to apply"- },- "metadata": {- "$ref": "#/components/schemas/CheckoutSessionMetadata",- "description": "Tracking metadata for conversion attribution"- },- "successUrl": {- "type": "string",- "description": "The URL to redirect to on successful checkout"- },- "tier": {- "$ref": "#/components/schemas/StripeProductTier",- "description": "The tier, defaults to haiku"- }- }- },"CreateCheckoutSessionV2Request": {"type": "object","description": "Request body for creating a Stripe checkout session",@@ -4081,17 +3913,6 @@}}},- "PatchSubscriptionTierRequest": {- "type": "object",- "description": "Request body for changing the user's subscription tier",- "required": ["newTier"],- "properties": {- "newTier": {- "$ref": "#/components/schemas/StripeProductTier",- "description": "The new tier to move the user to"- }- }- },"PatchTeamCrmSettingsRequest": {"type": "object","description": "Request body for `PATCH /team/crm`.",@@ -4322,10 +4143,6 @@}}},- "StripeProductTier": {- "type": "string",- "enum": ["haiku", "sonnet", "opus"]- },"StripeSessionResponse": {"type": "object","description": "Response containing the Stripe session URL",diff --git a/js/app/packages/service-clients/service-stripe/client.ts b/js/app/packages/service-clients/service-stripe/client.tsindex 03eaaa155b..a8d23d5727 100644--- a/js/app/packages/service-clients/service-stripe/client.ts+++ b/js/app/packages/service-clients/service-stripe/client.ts@@ -1,10 +1,5 @@import { registerClient } from '@core/util/mockClient';-import {- authServiceClient,- type PatchSubscriptionTierErrorCode,-} from '@service-auth/client';-import type { StripeProductTier } from '@service-auth/generated/schemas/stripeProductTier';-import { match, P } from 'ts-pattern';+import { authServiceClient } from '@service-auth/client';/*** Gets Meta _fbp (browser ID) and _fbc (click ID) values from cookies set by the Meta Pixel.@@ -132,40 +127,6 @@ export const stripeServiceClient = {return result.value;},- /**- * Changes the current user's subscription tier. Returns a narrow discriminated union so- * callers get a type-checked error `code` without drilling into the Result- * error array (`result.error?.[0]?.code`), which would silently fall through to the default case- * if the shape ever changes. Callers should invalidate the user info query on success.- */- updateSubscriptionTier: async (- tier: StripeProductTier- ): Promise<UpdateSubscriptionTierResult> => {- const result = await authServiceClient.patchSubscriptionTier({- newTier: tier,- });- if (result.isOk()) return { ok: true };- // Narrow the first error's code to our known union; anything else (NETWORK_ERROR,- // UNAUTHORIZED, SERVER_ERROR, etc.) collapses to 'UNKNOWN'. `match` + the explicit- // P.union of `PatchSubscriptionTierErrorCode` members means adding a new backend- // code without widening this union is a compile error.- const code = match(result.error[0]?.code)- .with(- P.union(- 'TIER_UNCHANGED',- 'USER_IN_TEAM',- 'NO_SUBSCRIPTION',- 'UPDATE_IN_PROGRESS'- ),- (c) => c- )- .otherwise(() => 'UNKNOWN' as const);- return { ok: false, code };- },};-type UpdateSubscriptionTierResult =- | { ok: true }- | { ok: false; code: PatchSubscriptionTierErrorCode | 'UNKNOWN' };-registerClient('stripe', stripeServiceClient);diff --git a/js/bun.lock b/js/bun.lockindex 0845698249..d8a2279d66 100644--- a/js/bun.lock+++ b/js/bun.lock@@ -2547,7 +2547,7 @@"pathval": ["[email protected]", "", {}, "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ=="],- "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6"],+ "pdfjs-dist": ["pdfjs-dist@github:macro-inc/pdf.js#f9b2ce6", { "dependencies": { "dommatrix": "^1.0.3", "web-streams-polyfill": "^3.2.1" }, "peerDependencies": { "worker-loader": "^3.0.8" }, "optionalPeers": ["worker-loader"] }, "macro-inc-pdf.js-f9b2ce6", "sha512-HDFaPbCxLG2GHpf1smUG97nku5aPGBGaCcIbK05dGdp07TBLUlDcXsM4WcE82mO5W4RBPIBVYobX5N/6M6NFrA=="],"performance-now": ["[email protected]", "", {}, "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow=="],diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rsindex ba32a62147..aff56fb293 100644--- a/rust/cloud-storage/authentication_service/src/api/context.rs+++ b/rust/cloud-storage/authentication_service/src/api/context.rs@@ -31,8 +31,6 @@ use roles_and_permissions::{};use sqlx::PgPool;-use crate::config::LegacyStripePriceIds;-pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsQueue>;pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<@@ -87,8 +85,6 @@ pub(crate) struct ApiContext {pub analytics_client: Arc<AnalyticsClient>,pub referral_service: Arc<ReferralServiceType>,pub rate_limit_service: RateLimiter,- /// The stripe price ids- pub legacy_stripe_price_ids: LegacyStripePriceIds,/// The stripe price idpub stripe_price_id: String,}diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rsindex 12e461abea..7e0c455850 100644--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs@@ -32,11 +32,9 @@ use crate::api::user::patch_user_group::PatchUserGroupRequest;use crate::api::user::patch_user_onboarding::PatchUserOnboardingRequest;use crate::api::user::post_get_names::PostGetNamesRequestBody;use crate::api::user::post_get_names_with_email::GetNamesWithEmailRequestBody;-use crate::api::user::stripe::create_checkout_session::CreateCheckoutSessionRequest;+use crate::api::user::stripe::StripeSessionResponse;use crate::api::user::stripe::create_checkout_session_v2::CreateCheckoutSessionV2Request;use crate::api::user::stripe::create_portal_session::CreatePortalSessionRequest;-use crate::api::user::stripe::patch_subscription_tier::PatchSubscriptionTierRequest;-use crate::api::user::stripe::{StripeProductTier, StripeSessionResponse};use crate::api::{email, github_pull_requests, health, jwt, link, login, logout, merge, mobile_welcome_email,oauth, oauth2, permissions, session, user,@@ -111,10 +109,8 @@ use model::user::{user::get_user_quota::handler,user::get_legacy_user_permissions::handler,user::patch_tutorial::handler,- user::stripe::create_checkout_session::create_checkout_session,user::stripe::create_checkout_session_v2::create_checkout_session,user::stripe::create_portal_session::create_portal_session,- user::stripe::patch_subscription_tier::patch_subscription_tier,/// /sessionsession::session_login::handler,@@ -197,11 +193,8 @@ use model::user::{PatchUserTutorialRequest,// Stripe- StripeProductTier,- CreateCheckoutSessionRequest,CreateCheckoutSessionV2Request,CreatePortalSessionRequest,- PatchSubscriptionTierRequest,StripeSessionResponse,// User onboardingdiff --git a/rust/cloud-storage/authentication_service/src/api/user/mod.rs b/rust/cloud-storage/authentication_service/src/api/user/mod.rsindex c19a38e339..c98209f17c 100644--- a/rust/cloud-storage/authentication_service/src/api/user/mod.rs+++ b/rust/cloud-storage/authentication_service/src/api/user/mod.rs@@ -57,10 +57,6 @@ fn router_with_auth(state: ApiContext, jwt_args: JwtValidationArgs) -> Router<Apmacro_middleware::user_permissions::attach_user_permissions::handler,)),)- .route(- "/stripe/checkout",- post(stripe::create_checkout_session::create_checkout_session),- ).route("/stripe/checkoutv2",post(@@ -73,10 +69,6 @@ fn router_with_auth(state: ApiContext, jwt_args: JwtValidationArgs) -> Router<Ap"/stripe/portal",post(stripe::create_portal_session::create_portal_session),)- .route(- "/stripe/subscription",- patch(stripe::patch_subscription_tier::patch_subscription_tier),- ).route("/legacy_user_permissions",get(get_legacy_user_permissions::handler),diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session.rsdeleted file mode 100644index f82ead3af0..0000000000--- a/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session.rs+++ /dev/null@@ -1,171 +0,0 @@-use axum::{Extension, Json, extract::State};-use serde::Deserialize;-use utoipa::ToSchema;--use super::{StripeOperationError, StripeProductTier, StripeSessionResponse};-use crate::api::context::ApiContext;-use model::response::ErrorResponse;-use model::user::UserContext;--/// Tracking metadata for conversion attribution-#[derive(Debug, Default, Deserialize, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct CheckoutSessionMetadata {- /// Google Analytics client ID for conversion tracking- pub ga_client_id: Option<String>,- /// Meta (Facebook) browser ID from _fbp cookie- pub fbp: Option<String>,- /// Meta (Facebook) click ID from _fbc cookie- pub fbc: Option<String>,-}--/// Request body for creating a Stripe checkout session-#[derive(Debug, Deserialize, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct CreateCheckoutSessionRequest {- /// The URL to redirect to on successful checkout- pub success_url: String,- /// The URL to redirect to if checkout is cancelled- pub cancel_url: String,- /// Optional discount/promo code to apply- pub discount: Option<String>,- /// Tracking metadata for conversion attribution- #[serde(default)]- pub metadata: CheckoutSessionMetadata,- /// The tier, defaults to haiku- #[serde(default)]- pub tier: StripeProductTier,-}--/// **LEGACY DO NOT USE** Creates a Stripe checkout session for the user to subscribe.-#[utoipa::path(- post,- path = "/user/stripe/checkout",- operation_id = "create_checkout_session",- request_body = CreateCheckoutSessionRequest,- responses(- (status = 200, body = StripeSessionResponse),- (status = 400, body = ErrorResponse),- (status = 404, body = ErrorResponse),- (status = 409, body = ErrorResponse),- (status = 500, body = ErrorResponse),- )-)]-#[tracing::instrument(skip(ctx, user_context), err, fields(user_id = %user_context.user_id))]-pub async fn create_checkout_session(- State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,- Json(req): Json<CreateCheckoutSessionRequest>,-) -> Result<Json<StripeSessionResponse>, StripeOperationError> {- let user_id =- macro_user_id::user_id::MacroUserId::parse_from_str(&user_context.user_id)?.lowercase();-- // Get the stripe customer ID from the database- let stripe_customer_id =- macro_db_client::user::get::get_stripe_customer_id_by_user_id(&ctx.db, &user_id)- .await?- .ok_or(StripeOperationError::MissingStripeId)?;-- 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 ID- let promo_code_id = if let Some(ref discount) = req.discount {- let mut list_params = stripe::ListPromotionCodes::new();- list_params.code = Some(discount);- list_params.active = Some(true);- list_params.limit = Some(1);-- let promo_codes = stripe::PromotionCode::list(&ctx.stripe_client, &list_params).await?;-- let promo_code = promo_codes- .data- .into_iter()- .next()- .ok_or(StripeOperationError::PromoCodeNotFound)?;-- Some(promo_code.id)- } else {- None- };-- // Build subscription metadata from optional tracking fields- let mut metadata = std::collections::HashMap::new();- if let Some(ga_client_id) = req.metadata.ga_client_id {- metadata.insert("ga_client_id".to_string(), ga_client_id);- }- if let Some(fbp) = req.metadata.fbp {- metadata.insert("fbp".to_string(), fbp);- }- if let Some(fbc) = req.metadata.fbc {- metadata.insert("fbc".to_string(), fbc);- }-- // Only set subscription_data if we have metadata to include- let subscription_data =- (!metadata.is_empty()).then_some(stripe::CreateCheckoutSessionSubscriptionData {- metadata: Some(metadata),- ..Default::default()- });-- let price_id = match req.tier {- StripeProductTier::Haiku => ctx.legacy_stripe_price_ids.stripe_price_id_haiku.as_ref(),- StripeProductTier::Sonnet => ctx.legacy_stripe_price_ids.stripe_price_id_sonnet.as_ref(),- StripeProductTier::Opus => ctx.legacy_stripe_price_ids.stripe_price_id_opus.as_ref(),- };-- // Create the checkout session- let params = stripe::CreateCheckoutSession {- customer: Some(customer_id),- mode: Some(stripe::CheckoutSessionMode::Subscription),- success_url: Some(req.success_url.as_str()),- cancel_url: Some(req.cancel_url.as_str()),- allow_promotion_codes: promo_code_id.is_none().then_some(true),- discounts: promo_code_id.map(|id| {- vec![stripe::CreateCheckoutSessionDiscounts {- promotion_code: Some(id.to_string()),- ..Default::default()- }]- }),- line_items: Some(vec![stripe::CreateCheckoutSessionLineItems {- price: Some(price_id.to_string()),- quantity: Some(1),- ..Default::default()- }]),- subscription_data,- ..Default::default()- };-- let session = stripe::CheckoutSession::create(&ctx.stripe_client, params).await?;-- let url = session- .url- .ok_or(StripeOperationError::UnexpectedStripeResponse)?;-- // Validate but return the exact URL Stripe gave us — session URLs are signed/opaque- // and `Url::parse(...).to_string()` can normalize in ways that break the signature.- url::Url::parse(&url).map_err(|_| StripeOperationError::UnexpectedStripeResponse)?;-- Ok(Json(StripeSessionResponse { url }))-}diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session_v2.rsindex b911ce9126..a1737d4dab 100644--- a/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs+++ b/rust/cloud-storage/authentication_service/src/api/user/stripe/create_checkout_session_v2.rs@@ -8,9 +8,20 @@ use utoipa::ToSchema;use super::{StripeOperationError, StripeSessionResponse};use crate::api::context::ApiContext;-use crate::api::user::stripe::create_checkout_session::CheckoutSessionMetadata;use model::response::ErrorResponse;+/// Tracking metadata for conversion attribution+#[derive(Debug, Default, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CheckoutSessionMetadata {+ /// Google Analytics client ID for conversion tracking+ pub ga_client_id: Option<String>,+ /// Meta (Facebook) browser ID from _fbp cookie+ pub fbp: Option<String>,+ /// Meta (Facebook) click ID from _fbc cookie+ pub fbc: Option<String>,+}+/// Request body for creating a Stripe checkout session#[derive(Debug, Deserialize, ToSchema)]#[serde(rename_all = "camelCase")]diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe/mod.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe/mod.rsindex 9f0c9122c7..97cfab6e38 100644--- a/rust/cloud-storage/authentication_service/src/api/user/stripe/mod.rs+++ b/rust/cloud-storage/authentication_service/src/api/user/stripe/mod.rs@@ -1,7 +1,5 @@-pub mod create_checkout_session;pub mod create_checkout_session_v2;pub mod create_portal_session;-pub mod patch_subscription_tier;mod shared;-pub use shared::{StripeOperationError, StripeProductTier, StripeSessionResponse};+pub use shared::{StripeOperationError, StripeSessionResponse};diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe/patch_subscription_tier.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe/patch_subscription_tier.rsdeleted file mode 100644index c083a4df78..0000000000--- a/rust/cloud-storage/authentication_service/src/api/user/stripe/patch_subscription_tier.rs+++ /dev/null@@ -1,332 +0,0 @@-use std::collections::HashSet;--use axum::{Extension, Json, extract::State};-use macro_user_id::user_id::MacroUserIdStr;-use roles_and_permissions::domain::{- model::{RoleId, UserRolesAndPermissionsError},- port::UserRolesAndPermissionsService,-};-use serde::Deserialize;-use strum::IntoEnumIterator;-use teams::domain::team_repo::TeamService;-use utoipa::ToSchema;--use super::{StripeOperationError, StripeProductTier};-use crate::api::context::ApiContext;-use crate::config::LegacyStripePriceIds;-use model::response::ErrorResponse;-use model::user::UserContext;--/// Request body for changing the user's subscription tier-#[derive(Debug, Deserialize, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct PatchSubscriptionTierRequest {- /// The new tier to move the user to- pub new_tier: StripeProductTier,-}--/// Updates the user's subscription tier, swapping both their RBAC role and Stripe subscription line item.-#[utoipa::path(- patch,- path = "/user/stripe/subscription",- operation_id = "patch_subscription_tier",- request_body = PatchSubscriptionTierRequest,- responses(- (status = 200),- (status = 400, body = ErrorResponse),- (status = 403, body = ErrorResponse),- (status = 404, body = ErrorResponse),- (status = 409, body = ErrorResponse),- (status = 500, body = ErrorResponse),- )-)]-#[tracing::instrument(skip(ctx, user_context), err, fields(user_id = %user_context.user_id))]-pub async fn patch_subscription_tier(- State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,- Json(req): Json<PatchSubscriptionTierRequest>,-) -> Result<(), StripeOperationError> {- let user_id = MacroUserIdStr::parse_from_str(&user_context.user_id)?;-- // Team members can't manage their own tier — the team owner's tier change flow- // (`PATCH /team/{id}/tier`) owns billing for the whole team. Checked before taking the- // lock so we don't pin a connection for a user who can't use this endpoint anyway.- if !ctx.teams_service.get_user_teams(&user_id).await?.is_empty() {- return Err(StripeOperationError::UserInTeam);- }-- // Serialize concurrent subscription mutations for this user (double-clicks, racing tabs,- // user + webhook). Lock is released when `txn` is committed or dropped at end of handler.- let mut txn = ctx.db.begin().await?;- if !macro_db_client::advisory_lock::try_acquire_user_subscription_xact_lock(&mut txn, &user_id)- .await?- {- return Err(StripeOperationError::SubscriptionUpdateInProgress);- }-- let new_tier = req.new_tier;- let new_price_id = price_id_for_tier(&ctx.legacy_stripe_price_ids, new_tier);-- let user_roles = ctx- .user_roles_and_permissions_service- .get_user_roles(&user_id)- .await?;-- let old_tier = find_current_sub_tier(&user_roles)?;-- if old_tier == new_tier {- return Err(StripeOperationError::TierUnchanged);- }-- let old_price_id = price_id_for_tier(&ctx.legacy_stripe_price_ids, old_tier);- let old_role = tier_to_sub_role(old_tier);- let new_role = tier_to_sub_role(new_tier);-- let stripe_customer_id =- macro_db_client::user::get::get_stripe_customer_id_by_user_id(&ctx.db, &user_id)- .await?- .ok_or(StripeOperationError::MissingStripeId)?;- let customer_id: stripe::CustomerId = stripe_customer_id.parse()?;-- let subscription = fetch_active_subscription(&ctx.stripe_client, customer_id).await?;- let old_item_id = find_subscription_item_id(&subscription, old_price_id)?;-- let roles_service = ctx.user_roles_and_permissions_service.as_ref();- swap_user_role(roles_service, &user_id, &old_role, &new_role).await?;-- // Stripe idempotency: guarantees a retried call (e.g. our 200 got lost in flight) won't- // double-apply the tier swap. Key is stable per logical operation; Stripe's own 24h TTL- // handles the "after some window, treat as new operation" case. Uses an explicit stable- // string for the tier (rather than `Debug`) so that renaming an enum variant doesn't- // rotate every in-flight key and break dedup.- let idempotency_key = format!(- "patch_subscription_tier:{user_id}:{}:{}:{}",- tier_key_str(old_tier),- tier_key_str(new_tier),- subscription.id,- );- let idempotent_client = ctx- .stripe_client- .as_ref()- .clone()- .with_strategy(stripe::RequestStrategy::Idempotent(idempotency_key.clone()));-- if let Err(stripe_err) = swap_subscription_item(- &idempotent_client,- &subscription.id,- &old_item_id,- new_price_id,- )- .await- {- // Include subscription id, prices, and idempotency key so on-call can reconcile:- // if Stripe actually applied the change server-side but returned a network error,- // we just rolled back RBAC and left it desynced. The idempotency key + subscription- // id uniquely identify the operation for manual inspection.- match rollback_role_swap(roles_service, &user_id, &old_role, &new_role).await {- Ok(()) => tracing::error!(- error = ?stripe_err,- subscription_id = %subscription.id,- old_price_id = old_price_id,- new_price_id = new_price_id,- idempotency_key = %idempotency_key,- "stripe subscription update failed, role swap rolled back",- ),- Err(rollback_err) => tracing::error!(- error = ?stripe_err,- rollback_error = ?rollback_err,- subscription_id = %subscription.id,- old_price_id = old_price_id,- new_price_id = new_price_id,- idempotency_key = %idempotency_key,- old_role = ?old_role,- new_role = ?new_role,- "stripe subscription update failed AND rollback failed — user state inconsistent",- ),- }- return Err(stripe_err.into());- }-- txn.commit().await?;- Ok(())-}--/// Maps a subscription tier to the RBAC role a user holds while subscribed at that tier.-fn tier_to_sub_role(tier: StripeProductTier) -> RoleId {- match tier {- StripeProductTier::Haiku => RoleId::SubHaiku,- StripeProductTier::Sonnet => RoleId::SubSonnet,- StripeProductTier::Opus => RoleId::SubOpus,- }-}--/// Stable string form of a tier for use in externally-visible keys (idempotency keys, etc.).-/// Must remain stable even if enum variants are renamed — otherwise in-flight idempotency-/// keys would rotate and dedup would break.-fn tier_key_str(tier: StripeProductTier) -> &'static str {- match tier {- StripeProductTier::Haiku => "haiku",- StripeProductTier::Sonnet => "sonnet",- StripeProductTier::Opus => "opus",- }-}--/// Returns the Stripe price ID configured for the given tier.-fn price_id_for_tier(price_ids: &LegacyStripePriceIds, tier: StripeProductTier) -> &str {- match tier {- StripeProductTier::Haiku => price_ids.stripe_price_id_haiku.as_ref(),- StripeProductTier::Sonnet => price_ids.stripe_price_id_sonnet.as_ref(),- StripeProductTier::Opus => price_ids.stripe_price_id_opus.as_ref(),- }-}--/// Identifies the user's current subscription tier by scanning their RBAC role set.-/// Refuses to guess if the user somehow holds more than one Sub\* role — a drifted state that-/// would otherwise let us pick arbitrarily and silently leave the other role behind.-#[tracing::instrument(skip(roles), err)]-fn find_current_sub_tier(- roles: &HashSet<RoleId>,-) -> Result<StripeProductTier, StripeOperationError> {- let matches: Vec<StripeProductTier> = StripeProductTier::iter()- .filter(|tier| roles.contains(&tier_to_sub_role(*tier)))- .collect();-- match matches.as_slice() {- [] => Err(StripeOperationError::NoSubscriptionRole),- [tier] => Ok(*tier),- tiers => {- tracing::error!(- tiers = ?tiers,- "user holds multiple Sub* roles — refusing to change tier",- );- Err(StripeOperationError::InconsistentSubscriptionRoles)- }- }-}--/// Fetches the customer's single active Stripe subscription. Solo users are expected to have-/// exactly one; this endpoint is blocked for team members earlier in the handler, so a customer-/// with zero active subs here is genuinely "nothing to patch" and surfaces as 404.-#[tracing::instrument(skip(stripe_client), err, fields(customer_id = %customer_id))]-async fn fetch_active_subscription(- stripe_client: &stripe::Client,- customer_id: stripe::CustomerId,-) -> Result<stripe::Subscription, StripeOperationError> {- let mut list_params = stripe::ListSubscriptions::new();- list_params.customer = Some(customer_id);- list_params.status = Some(stripe::SubscriptionStatusFilter::Active);- list_params.limit = Some(1);-- stripe::Subscription::list(stripe_client, &list_params)- .await?- .data- .into_iter()- .next()- .ok_or(StripeOperationError::NoActiveSubscription)-}--/// Finds the subscription line item whose price matches `price_id` and returns its id.-/// Returning `UnexpectedStripeResponse` here would indicate Stripe is in a state we don't model-/// (e.g. the user's role points at a tier their subscription no longer contains).-fn find_subscription_item_id(- subscription: &stripe::Subscription,- price_id: &str,-) -> Result<String, StripeOperationError> {- subscription- .items- .data- .iter()- .find(|item| {- item.price- .as_ref()- .map(|p| p.id.as_str() == price_id)- .unwrap_or(false)- })- .map(|item| item.id.to_string())- .ok_or(StripeOperationError::UnexpectedStripeResponse)-}--/// Swaps a user's subscription tier role: upserts `new_role`, then removes `old_role`.-///-/// Ordering matters: upsert-then-remove means a partial failure leaves the user with *both*-/// roles (transient multi-role state, caught by `find_current_sub_tier` on the next request),-/// whereas remove-then-upsert could leave them with *zero* Sub roles and locked out of their-/// plan.-#[tracing::instrument(skip(service), err, fields(user_id = %user_id, old_role = ?old_role, new_role = ?new_role))]-async fn swap_user_role<S: UserRolesAndPermissionsService>(- service: &S,- user_id: &MacroUserIdStr<'_>,- old_role: &RoleId,- new_role: &RoleId,-) -> Result<(), UserRolesAndPermissionsError> {- service- .dangerous_upsert_roles_for_user(user_id, one_role(new_role))- .await?;-- service- .dangerous_remove_roles_from_user(user_id, &one_role(old_role))- .await?;-- Ok(())-}--/// Wraps a single role in a `NonEmpty` slice. Infallible: the slice always has length 1.-fn one_role(role: &RoleId) -> non_empty::NonEmpty<&[RoleId]> {- non_empty::NonEmpty::new(std::slice::from_ref(role))- .expect("slice::from_ref always yields a non-empty slice")-}--/// Swaps the subscription's line item from `old_item_id` to a new item at `new_price_id`.-///-/// Uses delete-old + add-new (quantity 1) in a single `Subscription::update` call rather than-/// mutating the existing item's price, matching the pattern used by the teams tier-swap code-/// path. `AlwaysInvoice` proration bills the pro-rated difference immediately so the customer-/// isn't charged the full new rate on their next cycle.-#[tracing::instrument(- skip(stripe_client),- err,- fields(subscription_id = %subscription_id, old_item_id = old_item_id, new_price_id = new_price_id),-)]-async fn swap_subscription_item(- stripe_client: &stripe::Client,- subscription_id: &stripe::SubscriptionId,- old_item_id: &str,- new_price_id: &str,-) -> Result<(), stripe::StripeError> {- let update_params = stripe::UpdateSubscription {- items: Some(vec![- stripe::UpdateSubscriptionItems {- id: Some(old_item_id.to_string()),- deleted: Some(true),- ..Default::default()- },- stripe::UpdateSubscriptionItems {- price: Some(new_price_id.to_string()),- quantity: Some(1),- ..Default::default()- },- ]),- proration_behavior: Some(- stripe::generated::billing::subscription::SubscriptionProrationBehavior::AlwaysInvoice,- ),- ..Default::default()- };-- stripe::Subscription::update(stripe_client, subscription_id, update_params).await?;- Ok(())-}--/// Reverts the role swap after a failed Stripe update.-///-/// On failure the caller is responsible for logging — combining the rollback error with the-/// originating Stripe error in a single structured log line gives alerting a complete picture-/// of the inconsistent state.-#[tracing::instrument(skip(service), err, fields(user_id = %user_id, old_role = ?old_role, new_role = ?new_role))]-async fn rollback_role_swap<S: UserRolesAndPermissionsService>(- service: &S,- user_id: &MacroUserIdStr<'_>,- old_role: &RoleId,- new_role: &RoleId,-) -> Result<(), UserRolesAndPermissionsError> {- swap_user_role(service, user_id, new_role, old_role).await-}diff --git a/rust/cloud-storage/authentication_service/src/api/user/stripe/shared.rs b/rust/cloud-storage/authentication_service/src/api/user/stripe/shared.rsindex 6078d8288f..609fca64eb 100644--- a/rust/cloud-storage/authentication_service/src/api/user/stripe/shared.rs+++ b/rust/cloud-storage/authentication_service/src/api/user/stripe/shared.rs@@ -5,7 +5,7 @@ use axum::{};use model::response::ErrorResponse;use roles_and_permissions::domain::model::UserRolesAndPermissionsError;-use serde::{Deserialize, Serialize};+use serde::Serialize;use stripe::{ParseIdError, StripeError};use thiserror::Error;use utoipa::ToSchema;@@ -29,20 +29,8 @@ pub enum StripeOperationError {UnexpectedStripeResponse,#[error("User already has an active subscription")]AlreadySubscribed,- #[error("User does not have an active subscription")]- NoActiveSubscription,- #[error("User does not have a subscription tier role")]- NoSubscriptionRole,- #[error("User has multiple subscription tier roles")]- InconsistentSubscriptionRoles,- #[error("Another subscription update is already in progress for this user")]- SubscriptionUpdateInProgress,- #[error("User is a member of a team; tier is managed by the team owner")]- UserInTeam,#[error("Teams service error")]TeamsErr(#[from] teams::domain::model::TeamError),- #[error("Subscription is already on the requested tier")]- TierUnchanged,#[error("Roles and permissions error")]RolesErr(#[from] UserRolesAndPermissionsError),}@@ -61,15 +49,7 @@ impl IntoResponse for StripeOperationError {StripeOperationError::PromoCodeNotFound => StatusCode::NOT_FOUND,StripeOperationError::UnexpectedStripeResponse => StatusCode::INTERNAL_SERVER_ERROR,StripeOperationError::AlreadySubscribed => StatusCode::CONFLICT,- StripeOperationError::NoActiveSubscription => StatusCode::NOT_FOUND,- StripeOperationError::NoSubscriptionRole => StatusCode::NOT_FOUND,- StripeOperationError::InconsistentSubscriptionRoles => {- StatusCode::INTERNAL_SERVER_ERROR- }- StripeOperationError::SubscriptionUpdateInProgress => StatusCode::CONFLICT,- StripeOperationError::UserInTeam => StatusCode::FORBIDDEN,StripeOperationError::TeamsErr(_) => StatusCode::INTERNAL_SERVER_ERROR,- StripeOperationError::TierUnchanged => StatusCode::BAD_REQUEST,StripeOperationError::RolesErr(_) => StatusCode::INTERNAL_SERVER_ERROR,};(@@ -82,15 +62,6 @@ impl IntoResponse for StripeOperationError {}}-#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default, ToSchema, strum::EnumIter)]-#[serde(rename_all = "lowercase")]-pub enum StripeProductTier {- #[default]- Haiku,- Sonnet,- Opus,-}-/// Response containing the Stripe session URL#[derive(Debug, Serialize, ToSchema)]#[serde(rename_all = "camelCase")]diff --git a/rust/cloud-storage/authentication_service/src/config.rs b/rust/cloud-storage/authentication_service/src/config.rsindex 9df5514809..3276580824 100644--- a/rust/cloud-storage/authentication_service/src/config.rs+++ b/rust/cloud-storage/authentication_service/src/config.rs@@ -2,7 +2,6 @@ use std::sync::LazyLock;use anyhow::Context;pub use macro_env::Environment;-use macro_env_var::env_var;use macro_service_urls::DocumentStorageServiceUrl;// BASE_URL env var. This is validated when creating the config in main.rs@@ -93,25 +92,10 @@ pub struct Config {/// PostHog host (optional)pub posthog_host: Option<String>,- /// The legacy stripe price ids- pub legacy_stripe_price_ids: LegacyStripePriceIds,-/// The stripe price idpub stripe_price_id: String,}-env_var! {- #[derive(Clone)]- pub struct LegacyStripePriceIds {- #[derive(Clone)]- pub StripePriceIdHaiku,- #[derive(Clone)]- pub StripePriceIdSonnet,- #[derive(Clone)]- pub StripePriceIdOpus,- }-}-/// Grab the stripe product price id using the environmentfn get_stripe_price_id_from_environment(environment: Environment) -> String {// SAFETY: stripe price ids are not sensitive information so hard coding them here is simpler@@ -193,8 +177,6 @@ impl Config {let posthog_api_key = std::env::var("POSTHOG_API_KEY").ok();let posthog_host = std::env::var("POSTHOG_HOST").ok();- let legacy_stripe_price_ids = LegacyStripePriceIds::new()?;-let stripe_price_id = get_stripe_price_id_from_environment(environment);Ok(Config {@@ -228,7 +210,6 @@ impl Config {meta_test_event_code,posthog_api_key,posthog_host,- legacy_stripe_price_ids,stripe_price_id,})}diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rsindex 4fef6ddc1b..22ba2c4d4e 100644--- a/rust/cloud-storage/authentication_service/src/main.rs+++ b/rust/cloud-storage/authentication_service/src/main.rs@@ -342,7 +342,6 @@ async fn main() -> anyhow::Result<()> {},}),analytics_client: Arc::new(analytics_client),- legacy_stripe_price_ids: config.legacy_stripe_price_ids,stripe_price_id: config.stripe_price_id,},config.port,