A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
test(billing): trim stripe config, legacy price and rejoin tests
Hampusc44e89506f78
diff --git a/fluxer_api/src/api/billing/mappers/StripeToBillingMapper.test.ts b/fluxer_api/src/api/billing/mappers/StripeToBillingMapper.test.tsindex 65315241a..e7909830e 100644--- a/fluxer_api/src/api/billing/mappers/StripeToBillingMapper.test.ts+++ b/fluxer_api/src/api/billing/mappers/StripeToBillingMapper.test.ts@@ -26,11 +26,6 @@ function expectTupleGetValue(value: object, index: number, expected: unknown): v}describe('computeStripeUpdatedAt', () => {- it('returns a Date', () => {- const d = computeStripeUpdatedAt({created: NOW_UNIX});- expect(d).toBeInstanceOf(Date);- expect(d.getTime()).toBe(NOW_UNIX * 1000);- });it('prefers status_transitions over created', () => {const later = NOW_UNIX + 5000;const d = computeStripeUpdatedAt({created: NOW_UNIX, status_transitions: {paid_at: later}});diff --git a/fluxer_api/src/api/donation/tests/DonationRequestLink.test.ts b/fluxer_api/src/api/donation/tests/DonationRequestLink.test.tsindex 8b19c1116..22b0aab12 100644--- a/fluxer_api/src/api/donation/tests/DonationRequestLink.test.ts+++ b/fluxer_api/src/api/donation/tests/DonationRequestLink.test.ts@@ -46,14 +46,5 @@ describe('POST /donations/request-link', () => {const emails = await listTestEmails(harness, {recipient: unknownEmail});expect(emails).toHaveLength(0);});- test('magic link token is 64-character hex string', async () => {- await createDonor(TEST_DONOR_EMAIL);- await createDonationRequestLinkBuilder(harness).body({email: TEST_DONOR_EMAIL}).expect(204).execute();- const emails = await listTestEmails(harness, {recipient: TEST_DONOR_EMAIL});- const token = emails[0]?.metadata.token;- expect(token).toBeDefined();- expect(token).toHaveLength(64);- expect(token).toMatch(/^[0-9a-f]{64}$/);- });});});diff --git a/fluxer_api/src/api/donation/tests/DonationTestUtils.ts b/fluxer_api/src/api/donation/tests/DonationTestUtils.tsindex 0fcb3572a..2bbf2f9c4 100644--- a/fluxer_api/src/api/donation/tests/DonationTestUtils.ts+++ b/fluxer_api/src/api/donation/tests/DonationTestUtils.ts@@ -6,7 +6,7 @@ import {DONATION_CURRENCIES, type DonationCurrency} from '@fluxer/schema/src/domexport const TEST_DONOR_EMAIL = '[email protected]';export const TEST_MAGIC_LINK_TOKEN = 'a'.repeat(64);-export const DONATION_AMOUNTS = {+const DONATION_AMOUNTS = {STANDARD: 2500,} as const;export const DONATION_CURRENCY_VALUES = {@@ -20,9 +20,8 @@ export const DONATION_CURRENCY_VALUES = {DKK: DONATION_CURRENCIES[7],NOK: DONATION_CURRENCIES[8],} as const;-export const DONATION_INTERVALS = {+const DONATION_INTERVALS = {MONTH: 'month',- YEAR: 'year',} as const;interface DonationCheckoutRequestBody {diff --git a/fluxer_api/src/api/stripe/tests/BillingConfigCache.test.ts b/fluxer_api/src/api/stripe/tests/BillingConfigCache.test.tsindex 539c41292..dc8ffa84b 100644--- a/fluxer_api/src/api/stripe/tests/BillingConfigCache.test.ts+++ b/fluxer_api/src/api/stripe/tests/BillingConfigCache.test.ts@@ -133,39 +133,6 @@ describe('BillingConfigCache', () => {setStoredBillingConfig(originalStored);});- it('builds the env catalog for the nine hosted currencies from Config.stripe', () => {- const config = getEffectiveBillingConfig();- expect(config.catalogMode).toBe('env');- expect(config.prices).toEqual(expectedEnvCatalog());- expect(config.countryCurrencies).toEqual({});- expect(config.defaultCurrency).toBeNull();- expect(config.legacyPrices).toEqual({monthly_try: ['price_old_try']});- expect(config.enabled).toBe(true);- expect(config.secretKey).toBe('sk_test_fluxer');- expect(config.webhookSecret).toBe('whsec_test_fluxer');- });-- it('leaves unconfigured env currencies out of the catalog', () => {- stripe.prices = {monthlyUsd: 'price_a', yearlyUsd: 'price_b', gift1MonthSek: 'price_c'};- expect(getEffectiveBillingConfig().prices).toEqual({- USD: {monthly: 'price_a', yearly: 'price_b', gift_1_month: null, gift_1_year: null},- SEK: {monthly: null, yearly: null, gift_1_month: 'price_c', gift_1_year: null},- });- });-- it('reads env values at call time and changes the version when they change', () => {- const before = getEffectiveBillingConfig();- expect(getEffectiveBillingConfig()).toBe(before);- stripe.prices = {...ENV_PRICES, monthlyUsd: 'price_changed'};- const afterPrice = getEffectiveBillingConfig();- expect(afterPrice.prices.USD?.monthly).toBe('price_changed');- expect(afterPrice.version).not.toBe(before.version);- stripe.webhookSecret = 'whsec_rotated';- const afterSecret = getEffectiveBillingConfig();- expect(afterSecret.webhookSecret).toBe('whsec_rotated');- expect(afterSecret.version).not.toBe(afterPrice.version);- });-it('uses the operator catalog when stored prices are set', () => {setStoredBillingConfig(operatorConfig());const config = getEffectiveBillingConfig();@@ -403,31 +370,12 @@ describe('BillingConfigCache', () => {instance.selfHosted = true;});- afterEach(() => {- vi.restoreAllMocks();- });-it('remembers the previously effective env secret when a stored one replaces it', () => {getAcceptedWebhookSecrets();setStoredBillingConfig(operatorConfig({stripe_webhook_secret: 'whsec_first'}));expect(getAcceptedWebhookSecrets()).toEqual(['whsec_first', 'whsec_test_fluxer']);});- it('remembers the previous self-hosted webhook secret for 24 hours after a change', () => {- const start = Date.now();- const now = vi.spyOn(Date, 'now').mockReturnValue(start);- setStoredBillingConfig(operatorConfig({stripe_webhook_secret: 'whsec_first'}));- expect(getAcceptedWebhookSecrets()).toEqual(['whsec_first']);- setStoredBillingConfig(operatorConfig({stripe_webhook_secret: 'whsec_second'}));- expect(getAcceptedWebhookSecrets()).toEqual(['whsec_second', 'whsec_first']);- setStoredBillingConfig(operatorConfig({stripe_webhook_secret: 'whsec_second'}));- expect(getAcceptedWebhookSecrets()).toEqual(['whsec_second', 'whsec_first']);- now.mockReturnValue(start + 23 * 60 * 60 * 1000);- expect(getAcceptedWebhookSecrets()).toEqual(['whsec_second', 'whsec_first']);- now.mockReturnValue(start + 24 * 60 * 60 * 1000 + 1);- expect(getAcceptedWebhookSecrets()).toEqual(['whsec_second']);- });-it('drops a remembered secret once it becomes current again', () => {setStoredBillingConfig(operatorConfig({stripe_webhook_secret: 'whsec_first'}));setStoredBillingConfig(operatorConfig({stripe_webhook_secret: 'whsec_second'}));diff --git a/fluxer_api/src/api/stripe/tests/OperatorBillingCatalog.test.ts b/fluxer_api/src/api/stripe/tests/OperatorBillingCatalog.test.tsindex 00e47da5b..c1d1fc843 100644--- a/fluxer_api/src/api/stripe/tests/OperatorBillingCatalog.test.ts+++ b/fluxer_api/src/api/stripe/tests/OperatorBillingCatalog.test.ts@@ -15,10 +15,8 @@ import {setStoredBillingConfig,} from '@app/api/stripe/BillingConfigCache';import {getProductRegistry, ProductRegistry, ProductType} from '@app/api/stripe/ProductRegistry';-import {getStripeClient} from '@app/api/stripe/StripeClient';import {setupSyncStripeWebhookWorker, signStripeWebhook} from '@app/api/stripe/tests/StripeWebhookTestUtils';import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {NoopLogger} from '@app/api/test/mocks/NoopLogger';import {createMockWebhookPayload,createStripeApiHandlers,@@ -32,8 +30,6 @@ import processStripeWebhook from '@app/api/worker/tasks/ProcessStripeWebhook';import {setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';import type {PremiumStateResponse, PriceIdsResponse} from '@fluxer/schema/src/domains/premium/PremiumSchemas';-import type {WorkerTaskHelpers} from '@pkgs/worker/src/contracts/WorkerTask';-import {HttpResponse, http} from 'msw';import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, test} from 'vitest';const ENV_CURRENCIES = ['USD', 'EUR', 'BRL', 'DKK', 'INR', 'ISK', 'NOK', 'PLN', 'SEK', 'TRY'] as const;@@ -244,6 +240,16 @@ describe('operator billing catalog', () => {expect(sessionField(session, 'tax_id_collection')).toEqual({enabled: 'true'});});+ test('leaves a premium checkout at the lifetime Stripe gives it by default', async () => {+ const token = await createPurchaser();+ await createBuilder(harness, token)+ .post('/stripe/checkout/gift')+ .body({price_id: 'price_envgiftmonthusd'})+ .expect(HTTP_STATUS.OK)+ .execute();+ expect(stripeHandlers.spies.createdCheckoutSessions[0]?.expires_at).toBeUndefined();+ });+test('opens the portal with the stored customer on hosted without checking it first', async () => {server.use(...createStripeApiHandlers({customerShouldFail: true}).handlers);const account = await createAccount();@@ -496,45 +502,6 @@ describe('operator billing catalog', () => {});});- describe('stripe client', () => {- test('is shared while the secret stays the same and rebuilt when it changes', () => {- useOperatorBilling();- const first = getStripeClient();- expect(first).not.toBeNull();- expect(getStripeClient()).toBe(first);- setStoredBillingConfig(operatorBilling({stripe_secret_key: 'sk_test_operator_b'}));- const second = getStripeClient();- expect(second).not.toBeNull();- expect(second).not.toBe(first);- });-- test('sends requests with the currently stored secret key', async () => {- const authorizations: Array<string | null> = [];- server.use(- http.get('https://api.stripe.com/v1/prices/:id', ({request, params}) => {- authorizations.push(request.headers.get('authorization'));- return HttpResponse.json({id: params.id, object: 'price', unit_amount: 500, currency: 'gbp'});- }),- );- const suffix = crypto.randomBytes(4).toString('hex');- const pricesFor = (tag: string) => ({- GBP: {- monthly: `price_${tag}${suffix}monthly`,- yearly: `price_${tag}${suffix}yearly`,- gift_1_month: `price_${tag}${suffix}giftmonth`,- gift_1_year: `price_${tag}${suffix}giftyear`,- },- });- useOperatorBilling({stripe_secret_key: 'sk_test_rotate_a', prices: pricesFor('a')});- await createBuilder(harness, '').get('/premium/price-ids').expect(HTTP_STATUS.OK).execute();- setStoredBillingConfig(operatorBilling({stripe_secret_key: 'sk_test_rotate_b', prices: pricesFor('b')}));- await createBuilder(harness, '').get('/premium/price-ids').expect(HTTP_STATUS.OK).execute();- expect(authorizations.slice(0, 4).every((value) => value === 'Bearer sk_test_rotate_a')).toBe(true);- expect(authorizations.slice(4)).toHaveLength(4);- expect(authorizations.slice(4).every((value) => value === 'Bearer sk_test_rotate_b')).toBe(true);- });- });-describe('premium purchase availability', () => {test('reports purchases disabled while billing is inactive', async () => {Config.stripe.prices = {};diff --git a/fluxer_api/src/api/stripe/tests/ProductRegistryLegacyPrices.test.ts b/fluxer_api/src/api/stripe/tests/ProductRegistryLegacyPrices.test.tsindex e6a0d3571..76663f754 100644--- a/fluxer_api/src/api/stripe/tests/ProductRegistryLegacyPrices.test.ts+++ b/fluxer_api/src/api/stripe/tests/ProductRegistryLegacyPrices.test.ts@@ -285,85 +285,4 @@ describe('ProductRegistry - legacy prices', () => {});});});-- describe('malformed configuration', () => {- test('a slot whose value is a bare string is ignored and the rest still registers', () => {- const registry = buildRegistry(MOCK_PRICES, {- monthly_brl: 'price_legacy_bare_string' as unknown as Array<string>,- yearly_brl: [LEGACY_YEARLY_BRL],- });- expect(registry.getProduct('price_legacy_bare_string')).toBeNull();- // Not accidentally registered character by character either.- expect(registry.getProduct('p')).toBeNull();- expect(registry.getProduct(LEGACY_YEARLY_BRL)?.type).toBe(ProductType.YEARLY_SUBSCRIPTION);- });-- test('a slot with an unrecognised name is ignored and the rest still registers', () => {- const registry = buildRegistry(MOCK_PRICES, {- weekly_brl: ['legacy_weekly'],- visionary_usd: ['legacy_visionary'],- brl: ['legacy_no_separator'],- _brl: ['legacy_leading_separator'],- yearly_brl: [LEGACY_YEARLY_BRL],- });- expect(registry.getProduct('legacy_weekly')).toBeNull();- expect(registry.getProduct('legacy_visionary')).toBeNull();- expect(registry.getProduct('legacy_no_separator')).toBeNull();- expect(registry.getProduct('legacy_leading_separator')).toBeNull();- expect(registry.getProduct(LEGACY_YEARLY_BRL)?.type).toBe(ProductType.YEARLY_SUBSCRIPTION);- });-- test('a slot with an unknown currency is ignored and the rest still registers', () => {- const registry = buildRegistry(MOCK_PRICES, {- monthly_jpy: ['legacy_jpy'],- gift_1_year_gbp: ['legacy_gbp'],- monthly_brl: [LEGACY_MONTHLY_BRL],- });- expect(registry.getProduct('legacy_jpy')).toBeNull();- expect(registry.getProduct('legacy_gbp')).toBeNull();- expect(registry.getProduct(LEGACY_MONTHLY_BRL)?.currency).toBe('BRL');- });-- test('empty, blank and undefined entries inside a slot are skipped', () => {- const registry = buildRegistry(MOCK_PRICES, {- monthly_brl: ['', undefined as unknown as string, LEGACY_MONTHLY_BRL],- });- expect(registry.getProduct('')).toBeNull();- expect(registry.getProduct(LEGACY_MONTHLY_BRL)?.currency).toBe('BRL');- });-- test('an undefined slot value is ignored', () => {- const registry = buildRegistry(MOCK_PRICES, {- monthly_try: undefined,- monthly_brl: [LEGACY_MONTHLY_BRL],- });- expect(registry.getProduct(LEGACY_MONTHLY_BRL)?.currency).toBe('BRL');- });-- test('an array-valued legacy map is ignored without throwing', () => {- const registry = buildRegistry(MOCK_PRICES, [- 'price_legacy_array',- ] as unknown as typeof Config.stripe.legacyPrices);- expect(registry.getProduct('price_legacy_array')).toBeNull();- // The authored prices are untouched.- expect(registry.getProduct(MOCK_PRICES.monthlyBrl)?.currency).toBe('BRL');- expect(registry.getRecurringSubscriptionPriceId('monthly', 'BRL')).toBe(MOCK_PRICES.monthlyBrl);- });-- test('a string-valued legacy map is ignored without throwing', () => {- const registry = buildRegistry(MOCK_PRICES, 'nonsense' as unknown as typeof Config.stripe.legacyPrices);- expect(registry.getProduct('nonsense')).toBeNull();- expect(registry.getProduct(MOCK_PRICES.monthlyBrl)?.currency).toBe('BRL');- });-- test('a number-valued legacy map is ignored without throwing', () => {- const registry = buildRegistry(MOCK_PRICES, 42 as unknown as typeof Config.stripe.legacyPrices);- expect(registry.getProduct(MOCK_PRICES.monthlyBrl)?.currency).toBe('BRL');- });-- test('an absent or empty legacy map leaves the authored registry intact', () => {- expect(buildRegistry(MOCK_PRICES, undefined).getProduct(MOCK_PRICES.monthlyBrl)?.currency).toBe('BRL');- expect(buildRegistry(MOCK_PRICES, {}).getProduct(MOCK_PRICES.monthlyBrl)?.currency).toBe('BRL');- });- });});diff --git a/fluxer_api/src/api/stripe/tests/StripePremiumService.test.ts b/fluxer_api/src/api/stripe/tests/StripePremiumService.test.tsdeleted file mode 100644index 04fcb78cb..000000000--- a/fluxer_api/src/api/stripe/tests/StripePremiumService.test.ts+++ /dev/null@@ -1,63 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';-import {Config} from '@app/api/Config';-import {createGuild, createRole, getMember} from '@app/api/guild/tests/GuildTestUtils';-import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';-import {createBuilder} from '@app/api/test/TestRequestBuilder';-import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';-import {UserPremiumTypes} from '@fluxer/constants/src/UserConstants';-import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';--describe('StripePremiumService', () => {- let harness: ApiTestHarness;- let originalVisionariesGuildId: string | undefined;- let originalVisionariesGuildVisionaryRoleId: string | undefined;- beforeAll(async () => {- harness = await createApiTestHarness();- originalVisionariesGuildId = Config.instance.visionariesGuildId ?? undefined;- originalVisionariesGuildVisionaryRoleId = Config.instance.visionariesGuildVisionaryRoleId ?? undefined;- });- afterAll(async () => {- await harness.shutdown();- Config.instance.visionariesGuildId = originalVisionariesGuildId;- Config.instance.visionariesGuildVisionaryRoleId = originalVisionariesGuildVisionaryRoleId;- });- beforeEach(async () => {- await harness.resetData();- const owner = await createTestAccount(harness);- const visionariesGuild = await createGuild(harness, owner.token, 'Visionaries Test Guild');- const visionaryRole = await createRole(harness, owner.token, visionariesGuild.id, {name: 'Visionary'});- Config.instance.visionariesGuildId = visionariesGuild.id;- Config.instance.visionariesGuildVisionaryRoleId = visionaryRole.id;- });- describe('POST /premium/visionary/rejoin', () => {- test('allows visionary users to rejoin guild', async () => {- const account = await createTestAccount(harness);- await createBuilder(harness, account.token)- .post(`/test/users/${account.userId}/premium`)- .body({- premium_type: UserPremiumTypes.LIFETIME,- premium_lifetime_sequence: 0,- })- .execute();- await createBuilder(harness, account.token).post('/premium/visionary/rejoin').expect(204).execute();- const member = await getMember(harness, account.token, Config.instance.visionariesGuildId!, account.userId);- expect(member.roles).toContain(Config.instance.visionariesGuildVisionaryRoleId);- });- test('rejects users without visionary access', async () => {- const account = await createTestAccount(harness);- await createBuilder(harness, account.token)- .post(`/test/users/${account.userId}/premium`)- .body({- premium_type: UserPremiumTypes.SUBSCRIPTION,- premium_until: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),- })- .execute();- await createBuilder(harness, account.token)- .post('/premium/visionary/rejoin')- .expect(403, APIErrorCodes.MISSING_ACCESS)- .execute();- });- });-});