Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

test(billing): cover self-service refunds for play and stripe

Hampusfcd0e128e186
diff --git a/fluxer_api/src/api/store_billing/tests/GooglePlaySelfServeRefund.test.ts b/fluxer_api/src/api/store_billing/tests/GooglePlaySelfServeRefund.test.ts
new file mode 100644
index 000000000..2ff3ed42f
--- /dev/null
+++ b/fluxer_api/src/api/store_billing/tests/GooglePlaySelfServeRefund.test.ts
@@ -0,0 +1,250 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {randomUUID} from 'node:crypto';
+import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {Config} from '@app/api/Config';
+import {getStoreBillingRepository, getUserRepository} from '@app/api/middleware/ServiceSingletons';
+import {buildGooglePlayStoreKey} from '@app/api/store_billing/StoreBillingTypes';
+import {
+ findUser,
+ getStoreContext,
+ installStoreBillingWorker,
+ uninstallStoreBillingWorker,
+} from '@app/api/store_billing/tests/StoreBillingTestUtils';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {
+ buildFakeProductPurchase,
+ buildFakeSubscriptionPurchase,
+ createGooglePlayDeveloperApiHandlers,
+ type FakeGooglePlayDeveloperApi,
+} from '@app/api/test/msw/handlers/GooglePlayDeveloperApiHandlers';
+import {createStripeApiHandlers} from '@app/api/test/msw/handlers/StripeApiHandlers';
+import {server} from '@app/api/test/msw/server';
+import {createBuilder} from '@app/api/test/TestRequestBuilder';
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
+import type {
+ PremiumStateResponse,
+ SelfServeRefundEligibilityResponse,
+ SelfServeRefundResponse,
+} from '@fluxer/schema/src/domains/premium/PremiumSchemas';
+import type {StorePurchaseClaimResponse} from '@fluxer/schema/src/domains/premium/StoreBillingSchemas';
+import {ms} from 'itty-time';
+import {HttpResponse, http} from 'msw';
+import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
+
+const PACKAGE_NAME = 'com.fluxer';
+const SUBSCRIPTION_PRODUCT = 'plutonium';
+const STRIPE_CUSTOMER_ID = 'cus_play_refund';
+
+describe('Google Play self-service refunds', () => {
+ let harness: ApiTestHarness;
+ let fake: FakeGooglePlayDeveloperApi;
+ const configured = Config.googlePlay.selfServiceRefunds;
+
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ fake = createGooglePlayDeveloperApiHandlers();
+ });
+
+ afterAll(async () => {
+ await harness.shutdown();
+ });
+
+ beforeEach(async () => {
+ await harness.resetData();
+ fake.reset();
+ server.use(...createStripeApiHandlers().handlers, ...fake.handlers);
+ installStoreBillingWorker();
+ Config.googlePlay.selfServiceRefunds = true;
+ });
+
+ afterEach(() => {
+ Config.googlePlay.selfServiceRefunds = configured;
+ uninstallStoreBillingWorker();
+ server.resetHandlers();
+ });
+
+ async function claimSubscription(
+ account: TestAccount,
+ options: {startedAgo: number; expiresIn: number},
+ ): Promise<{purchaseToken: string; orderId: string}> {
+ const purchaseToken = `token-${randomUUID()}`;
+ const orderId = `GPA.${randomUUID()}`;
+ const accountToken = (await getStoreContext(harness, account.token)).app_account_token;
+ fake.setSubscription(
+ PACKAGE_NAME,
+ purchaseToken,
+ buildFakeSubscriptionPurchase({
+ startTime: new Date(Date.now() - options.startedAgo).toISOString(),
+ externalAccountIdentifiers: {obfuscatedExternalAccountId: accountToken},
+ lineItems: [
+ {
+ productId: SUBSCRIPTION_PRODUCT,
+ expiryTime: new Date(Date.now() + options.expiresIn).toISOString(),
+ latestSuccessfulOrderId: orderId,
+ autoRenewingPlan: {autoRenewEnabled: true},
+ offerDetails: {basePlanId: 'monthly'},
+ },
+ ],
+ }),
+ );
+ await createBuilder<StorePurchaseClaimResponse>(harness, account.token)
+ .post('/premium/store/google-play/purchases')
+ .body({purchase_token: purchaseToken, product_id: SUBSCRIPTION_PRODUCT, package_name: PACKAGE_NAME})
+ .execute();
+ return {purchaseToken, orderId};
+ }
+
+ async function claimGift(account: TestAccount): Promise<{orderId: string; giftCode: string}> {
+ const purchaseToken = `token-${randomUUID()}`;
+ const orderId = `GPA.${randomUUID()}`;
+ fake.setProduct(PACKAGE_NAME, purchaseToken, buildFakeProductPurchase({orderId}));
+ const result = await createBuilder<StorePurchaseClaimResponse>(harness, account.token)
+ .post('/premium/store/google-play/purchases')
+ .body({purchase_token: purchaseToken, product_id: 'gift_1_month', package_name: PACKAGE_NAME})
+ .execute();
+ return {orderId, giftCode: result.gift_code!};
+ }
+
+ function eligibility(account: TestAccount): Promise<SelfServeRefundEligibilityResponse> {
+ return createBuilder<SelfServeRefundEligibilityResponse>(harness, account.token)
+ .get('/premium/refund-eligibility')
+ .execute();
+ }
+
+ function refund(account: TestAccount): Promise<SelfServeRefundResponse> {
+ return createBuilder<SelfServeRefundResponse>(harness, account.token).post('/premium/refund-latest').execute();
+ }
+
+ it('refunds a new Google Play subscription and ends access right away', async () => {
+ const account = await createTestAccount(harness);
+ const {purchaseToken, orderId} = await claimSubscription(account, {
+ startedAgo: ms('1 hour'),
+ expiresIn: ms('29 days'),
+ });
+ expect((await findUser(account.userId)).isPremium()).toBe(true);
+
+ const before = await eligibility(account);
+ expect(before).toMatchObject({
+ eligible: true,
+ reason: null,
+ provider: 'google_play',
+ invoice_id: orderId,
+ cancels_subscription: true,
+ });
+ const state = await createBuilder<PremiumStateResponse>(harness, account.token).get('/premium/state').execute();
+ expect(state.billing.refund_eligibility).toMatchObject({eligible: true, provider: 'google_play'});
+
+ const result = await refund(account);
+
+ expect(result).toMatchObject({provider: 'google_play', invoice_id: orderId, status: 'succeeded'});
+ expect(fake.spies.refunded).toEqual([{packageName: PACKAGE_NAME, orderId, revoke: true}]);
+ const user = await findUser(account.userId);
+ const row = await getStoreBillingRepository().findPurchase(buildGooglePlayStoreKey(purchaseToken));
+ expect(row).toMatchObject({entitled: false, state: 'revoked'});
+ expect(user.premiumUntil).toEqual(row!.revoked_at);
+ expect(user.premiumGraceEndsAt).toEqual(row!.revoked_at);
+ expect(user.premiumUntil!.getTime()).toBeLessThanOrEqual(Date.now());
+ expect(user.lastRefundAt).not.toBeNull();
+ expect((await eligibility(account)).eligible).toBe(false);
+ });
+
+ it('does not refund a Google Play subscription charged more than three days ago', async () => {
+ const account = await createTestAccount(harness);
+ await claimSubscription(account, {startedAgo: ms('10 days'), expiresIn: ms('20 days')});
+
+ expect(await eligibility(account)).toMatchObject({eligible: false, reason: 'outside_refund_window'});
+ await createBuilder(harness, account.token)
+ .post('/premium/refund-latest')
+ .expect(403, APIErrorCodes.STRIPE_REFUND_OUTSIDE_WINDOW)
+ .execute();
+ expect(fake.spies.refunded).toEqual([]);
+ });
+
+ it('refunds an unredeemed Google Play gift and revokes its code', async () => {
+ const account = await createTestAccount(harness);
+ const {orderId, giftCode} = await claimGift(account);
+
+ expect(await eligibility(account)).toMatchObject({eligible: true, cancels_subscription: false});
+ await refund(account);
+
+ expect(fake.spies.refunded).toEqual([{packageName: PACKAGE_NAME, orderId, revoke: true}]);
+ expect((await getUserRepository().findGiftCode(giftCode))?.revokedAt).not.toBeNull();
+ });
+
+ it('does not refund a Google Play gift that was already redeemed', async () => {
+ const account = await createTestAccount(harness);
+ const friend = await createTestAccount(harness);
+ const {giftCode} = await claimGift(account);
+ await createBuilder(harness, friend.token).post(`/gifts/${giftCode}/redeem`).expect(204).execute();
+
+ expect(await eligibility(account)).toMatchObject({eligible: false, reason: 'no_refundable_purchase'});
+ await createBuilder(harness, account.token)
+ .post('/premium/refund-latest')
+ .expect(400, APIErrorCodes.STRIPE_NO_PURCHASE_HISTORY)
+ .execute();
+ expect(fake.spies.refunded).toEqual([]);
+ });
+
+ it('offers no Google Play refund while the setting is off', async () => {
+ Config.googlePlay.selfServiceRefunds = false;
+ const account = await createTestAccount(harness);
+ await claimSubscription(account, {startedAgo: ms('1 hour'), expiresIn: ms('29 days')});
+
+ expect((await eligibility(account)).eligible).toBe(false);
+ await createBuilder(harness, account.token)
+ .post('/premium/refund-latest')
+ .expect(400, APIErrorCodes.STRIPE_NO_PURCHASE_HISTORY)
+ .execute();
+ expect(fake.spies.refunded).toEqual([]);
+ });
+
+ it('refunds whichever of a Stripe invoice and a Google Play purchase is newer', async () => {
+ const account = await createTestAccount(harness);
+ await createBuilder(harness, account.token)
+ .post(`/test/users/${account.userId}/premium`)
+ .body({stripe_customer_id: STRIPE_CUSTOMER_ID})
+ .execute();
+ const paidAt = Math.floor((Date.now() - ms('2 days')) / 1000);
+ server.use(
+ http.get('https://api.stripe.com/v1/invoices', () =>
+ HttpResponse.json({
+ object: 'list',
+ has_more: false,
+ url: '/v1/invoices',
+ data: [
+ {
+ id: 'in_older',
+ object: 'invoice',
+ customer: STRIPE_CUSTOMER_ID,
+ parent: null,
+ amount_due: 499,
+ amount_paid: 499,
+ currency: 'usd',
+ status: 'paid',
+ created: paidAt,
+ payments: {
+ object: 'list',
+ has_more: false,
+ url: '/v1/invoices/in_older/payments',
+ data: [
+ {
+ id: 'inpay_older',
+ invoice: 'in_older',
+ object: 'invoice_payment',
+ status: 'paid',
+ status_transitions: {paid_at: paidAt},
+ payment: {charge: 'ch_older', payment_intent: 'pi_older', type: 'payment_intent'},
+ },
+ ],
+ },
+ },
+ ],
+ }),
+ ),
+ );
+ const {orderId} = await claimSubscription(account, {startedAgo: ms('1 hour'), expiresIn: ms('29 days')});
+
+ expect(await eligibility(account)).toMatchObject({provider: 'google_play', invoice_id: orderId});
+ });
+});
diff --git a/fluxer_api/src/api/stripe/tests/StripeRefundService.test.ts b/fluxer_api/src/api/stripe/tests/StripeRefundService.test.ts
index e07369256..6ef97e223 100644
--- a/fluxer_api/src/api/stripe/tests/StripeRefundService.test.ts
+++ b/fluxer_api/src/api/stripe/tests/StripeRefundService.test.ts
@@ -130,6 +130,7 @@ function refundCreateHandler(opts?: {
amount: Number.parseInt((params.amount as string) ?? '0', 10),
currency: 'usd',
status: opts?.status ?? 'succeeded',
+ created: Math.floor(Date.now() / 1000),
failure_reason: opts?.failureReason ?? null,
payment_intent: params.payment_intent ?? null,
charge: params.charge ?? null,
@@ -263,6 +264,83 @@ describe('StripeRefundService self-serve refund', () => {
.expect(403, APIErrorCodes.STRIPE_REFUND_COOLDOWN_ACTIVE)
.execute();
});
+ test('accepts a refund just inside the 3-day window', async () => {
+ server.use(...createStripeApiHandlers().handlers);
+ server.use(
+ invoiceListHandler([
+ buildInvoice({id: 'in_edge', paidAtSecondsAgo: 3 * SECONDS_PER_DAY - 60, subscriptionId: null}),
+ ]),
+ refundCreateHandler(),
+ );
+ const account = await createTestAccount(harness);
+ await setStripeIds(harness, account, {stripe_customer_id: MOCK_CUSTOMER_ID});
+ const response = await createBuilder<SelfServeRefundResponse>(harness, account.token)
+ .post('/premium/refund-latest')
+ .execute();
+ expect(response.status).toBe('succeeded');
+ });
+ test('rejects a refund just past the 3-day window', async () => {
+ server.use(...createStripeApiHandlers().handlers);
+ server.use(invoiceListHandler([buildInvoice({id: 'in_edge', paidAtSecondsAgo: 3 * SECONDS_PER_DAY + 60})]));
+ const account = await createTestAccount(harness);
+ await setStripeIds(harness, account, {stripe_customer_id: MOCK_CUSTOMER_ID});
+ await createBuilder(harness, account.token)
+ .post('/premium/refund-latest')
+ .expect(403, APIErrorCodes.STRIPE_REFUND_OUTSIDE_WINDOW)
+ .execute();
+ });
+ test('rejects a refund when the last one was just under 30 days ago', async () => {
+ server.use(...createStripeApiHandlers().handlers);
+ server.use(invoiceListHandler([buildInvoice({id: 'in_recent', paidAtSecondsAgo: SECONDS_PER_DAY})]));
+ const account = await createTestAccount(harness);
+ const lastRefundAt = new Date(Date.now() - (30 * SECONDS_PER_DAY - 60) * 1000);
+ await setStripeIds(harness, account, {
+ stripe_customer_id: MOCK_CUSTOMER_ID,
+ first_refund_at: lastRefundAt.toISOString(),
+ });
+ const eligibility = await createBuilder<SelfServeRefundEligibilityResponse>(harness, account.token)
+ .get('/premium/refund-eligibility')
+ .execute();
+ expect(eligibility.eligible).toBe(false);
+ expect(eligibility.reason).toBe('cooldown_active');
+ expect(eligibility.cooldown_expires_at).toBe(
+ new Date(lastRefundAt.getTime() + 30 * SECONDS_PER_DAY * 1000).toISOString(),
+ );
+ await createBuilder(harness, account.token)
+ .post('/premium/refund-latest')
+ .expect(403, APIErrorCodes.STRIPE_REFUND_COOLDOWN_ACTIVE)
+ .execute();
+ });
+ test('allows another refund once 30 days have passed, never blocks purchases, and restarts the cooldown', async () => {
+ server.use(...createStripeApiHandlers().handlers);
+ server.use(
+ invoiceListHandler([buildInvoice({id: 'in_recent', paidAtSecondsAgo: SECONDS_PER_DAY, subscriptionId: null})]),
+ refundCreateHandler({refundId: 're_second_window'}),
+ );
+ const account = await createTestAccount(harness);
+ const userId = createUserID(BigInt(account.userId));
+ const lastRefundAt = new Date(Date.now() - (30 * SECONDS_PER_DAY + 60) * 1000);
+ await setStripeIds(harness, account, {
+ stripe_customer_id: MOCK_CUSTOMER_ID,
+ first_refund_at: lastRefundAt.toISOString(),
+ });
+ const eligibility = await createBuilder<SelfServeRefundEligibilityResponse>(harness, account.token)
+ .get('/premium/refund-eligibility')
+ .execute();
+ expect(eligibility.eligible).toBe(true);
+ expect(eligibility.cooldown_expires_at).toBeNull();
+ const response = await createBuilder<SelfServeRefundResponse>(harness, account.token)
+ .post('/premium/refund-latest')
+ .execute();
+ expect(response.status).toBe('succeeded');
+ const updatedUser = await new UserRepository().findUnique(userId);
+ expect(updatedUser!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(0);
+ expect(updatedUser!.lastRefundAt!.getTime()).toBeGreaterThan(Date.now() - 60 * 1000);
+ await createBuilder(harness, account.token)
+ .post('/premium/refund-latest')
+ .expect(403, APIErrorCodes.STRIPE_REFUND_COOLDOWN_ACTIVE)
+ .execute();
+ });
test('rejects when there is no refundable purchase', async () => {
server.use(...createStripeApiHandlers().handlers);
const account = await createTestAccount(harness);
@@ -290,7 +368,7 @@ describe('StripeRefundService self-serve refund', () => {
expect(response.subscription_id).toBeNull();
const {UserRepository} = await import('@app/api/user/repositories/UserRepository');
const updatedUser = await new UserRepository().findUnique(createUserID(BigInt(account.userId)));
- expect(updatedUser!.firstRefundAt).toBeNull();
+ expect(updatedUser!.lastRefundAt).toBeNull();
});
test('does not finalize cooldown or cancel the subscription when the refund fails at the provider', async () => {
server.use(...createStripeApiHandlers().handlers);
@@ -311,9 +389,9 @@ describe('StripeRefundService self-serve refund', () => {
expect(response.subscription_id).toBeNull();
const {UserRepository} = await import('@app/api/user/repositories/UserRepository');
const updatedUser = await new UserRepository().findUnique(createUserID(BigInt(account.userId)));
- expect(updatedUser!.firstRefundAt).toBeNull();
+ expect(updatedUser!.lastRefundAt).toBeNull();
});
- test('counts one self-serve refund once even when charge.refunded arrives afterwards and is retried', async () => {
+ test('starts the cooldown once even when charge.refunded arrives afterwards and is retried', async () => {
server.use(...createStripeApiHandlers().handlers);
const invoice = buildInvoice({
id: 'in_cross_path',
@@ -331,7 +409,7 @@ describe('StripeRefundService self-serve refund', () => {
expect(response.status).toBe('succeeded');
const userRepository = new UserRepository();
const afterSelfServe = await userRepository.findUnique(userId);
- expect(afterSelfServe!.firstRefundAt).not.toBeNull();
+ expect(afterSelfServe!.lastRefundAt).not.toBeNull();
expect(afterSelfServe!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(0);
const chargeEvent = {
type: 'charge.refunded' as const,
@@ -369,10 +447,10 @@ describe('StripeRefundService self-serve refund', () => {
await sendStripeWebhook(harness, {...chargeEvent, id: 'evt_cross_path_1'});
await sendStripeWebhook(harness, {...chargeEvent, id: 'evt_cross_path_2'});
const afterWebhook = await userRepository.findUnique(userId);
- expect(afterWebhook!.firstRefundAt!.getTime()).toBe(afterSelfServe!.firstRefundAt!.getTime());
+ expect(afterWebhook!.lastRefundAt!.getTime()).toBe(afterSelfServe!.lastRefundAt!.getTime());
expect(afterWebhook!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(0);
});
- test('counts one self-serve refund once even when refund.updated confirms it after the endpoint already did', async () => {
+ test('starts the cooldown once even when refund.updated confirms it after the endpoint already did', async () => {
server.use(...createStripeApiHandlers().handlers);
const invoice = buildInvoice({
id: 'in_double_confirm',
@@ -386,7 +464,7 @@ describe('StripeRefundService self-serve refund', () => {
await createBuilder<SelfServeRefundResponse>(harness, account.token).post('/premium/refund-latest').execute();
const userRepository = new UserRepository();
const afterSelfServe = await userRepository.findUnique(userId);
- expect(afterSelfServe!.firstRefundAt).not.toBeNull();
+ expect(afterSelfServe!.lastRefundAt).not.toBeNull();
await sendStripeWebhook(harness, {
id: 'evt_double_confirm_1',
type: 'refund.updated',
@@ -397,6 +475,7 @@ describe('StripeRefundService self-serve refund', () => {
status: 'succeeded',
amount: 2500,
currency: 'usd',
+ created: Math.floor(afterSelfServe!.lastRefundAt!.getTime() / 1000),
metadata: {
refund_kind: 'self_serve',
user_id: account.userId,
@@ -406,7 +485,7 @@ describe('StripeRefundService self-serve refund', () => {
},
});
const afterWebhook = await userRepository.findUnique(userId);
- expect(afterWebhook!.firstRefundAt!.getTime()).toBe(afterSelfServe!.firstRefundAt!.getTime());
+ expect(afterWebhook!.lastRefundAt!.getTime()).toBe(afterSelfServe!.lastRefundAt!.getTime());
expect(afterWebhook!.premiumFlags & PremiumFlags.PURCHASE_DISABLED).toBe(0);
});
test('retries with a fresh idempotency key once a prior attempt has failed at the provider', async () => {