A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
// SPDX-License-Identifier: AGPL-3.0-or-later
import crypto from 'node:crypto';
import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import type {UserID} from '@app/api/BrandedTypes';
import {Config} from '@app/api/Config';
import {createOperatorPassServices, type OperatorPassServices} from '@app/api/middleware/OperatorPassServiceFactory';
import {
getBillingRepository,
getGatewayService,
getSnowflakeService,
setInjectedWorkerService,
} from '@app/api/middleware/ServiceRegistry';
import {
createUserCacheService,
getAdminRepository,
getCacheService,
getDonationRepository,
getEmailService,
getGuildRepository,
getKVAccountDeletionQueue,
getOperatorPassRepository,
getPremiumStateReconciliationQueueService,
getUserRepository,
} from '@app/api/middleware/ServiceSingletons';
import {STRIPE_API_VERSION} from '@app/api/stripe/StripeApiVersion';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
import {createMockWebhookPayload, type StripeWebhookEventData} from '@app/api/test/msw/handlers/StripeApiHandlers';
import {SyncTaskWorkerService} from '@app/api/test/SyncTaskWorkerService';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {PaymentRepository} from '@app/api/user/repositories/PaymentRepository';
import closePaymentDisputeAccounts from '@app/api/worker/tasks/ClosePaymentDisputeAccounts';
import processStripeWebhook from '@app/api/worker/tasks/ProcessStripeWebhook';
import sendBillingEmail from '@app/api/worker/tasks/SendBillingEmail';
import {getWorkerDependencies, setWorkerDependenciesForTest} from '@app/api/worker/WorkerContext';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import Stripe from 'stripe';
export async function createTestUserWithPremium(
harness: ApiTestHarness,
premiumType: number,
options?: {
email?: string;
username?: string;
premiumUntil?: Date;
stripeCustomerId?: string;
stripeSubscriptionId?: string;
},
): Promise<TestAccount> {
const account = await createTestAccount(harness, {
email: options?.email,
username: options?.username,
});
await createBuilder(harness, account.token)
.post(`/test/users/${account.userId}/premium`)
.body({
premium_type: premiumType,
premium_until: options?.premiumUntil?.toISOString() || null,
stripe_customer_id: options?.stripeCustomerId || null,
stripe_subscription_id: options?.stripeSubscriptionId || null,
})
.execute();
return account;
}
export async function createTestPayment(
_harness: ApiTestHarness,
userId: UserID,
sessionId: string,
options?: {
priceId?: string;
productType?: string;
status?: string;
isGift?: boolean;
giftCode?: string;
stripeCustomerId?: string;
paymentIntentId?: string;
subscriptionId?: string;
},
): Promise<void> {
const paymentRepository = new PaymentRepository();
await paymentRepository.createPayment({
checkout_session_id: sessionId,
user_id: userId,
price_id: options?.priceId || 'price_test_monthly',
product_type: options?.productType || 'monthly_subscription',
status: options?.status || 'pending',
is_gift: options?.isGift || false,
created_at: new Date(),
});
await paymentRepository.updatePayment({
checkout_session_id: sessionId,
gift_code: options?.giftCode || null,
payment_intent_id: options?.paymentIntentId || null,
stripe_customer_id: options?.stripeCustomerId || null,
subscription_id: options?.subscriptionId || null,
});
}
export function setupSyncStripeWebhookWorker(): void {
const stripe = new Stripe(Config.stripe.secretKey || 'sk_test_fake', {
apiVersion: STRIPE_API_VERSION,
httpClient: Stripe.createFetchHttpClient(),
});
let operatorPassServices: OperatorPassServices | undefined;
setWorkerDependenciesForTest({
stripe,
operatorPassRepository: getOperatorPassRepository(),
get operatorPassServices() {
operatorPassServices ??= createOperatorPassServices(getWorkerDependencies());
return operatorPassServices;
},
userRepository: getUserRepository(),
userCacheService: createUserCacheService(),
emailService: getEmailService(),
gatewayService: getGatewayService(),
cacheService: getCacheService(),
guildRepository: getGuildRepository(),
donationRepository: getDonationRepository(),
deletionQueueService: getKVAccountDeletionQueue(),
premiumStateReconciliationQueueService: getPremiumStateReconciliationQueueService(),
adminRepository: getAdminRepository(),
snowflakeService: getSnowflakeService(),
billingRepository: getBillingRepository(),
});
setInjectedWorkerService(
new SyncTaskWorkerService({processStripeWebhook, closePaymentDisputeAccounts, sendBillingEmail}),
);
}
let originalWebhookSecretDescriptor: PropertyDescriptor | undefined;
export function mockStripeWebhookSecret(secret = 'whsec_test'): void {
originalWebhookSecretDescriptor ??= Object.getOwnPropertyDescriptor(Config.stripe, 'webhookSecret');
Object.defineProperty(Config.stripe, 'webhookSecret', {
get: () => secret,
configurable: true,
});
}
export function restoreStripeWebhookSecret(): void {
if (originalWebhookSecretDescriptor) {
Object.defineProperty(Config.stripe, 'webhookSecret', originalWebhookSecretDescriptor);
originalWebhookSecretDescriptor = undefined;
return;
}
delete (
Config.stripe as {
webhookSecret?: string;
}
).webhookSecret;
}
export function signStripeWebhook(payload: string, timestamp: number, secret: string): string {
const signature = crypto.createHmac('sha256', secret).update(`${timestamp}.${payload}`).digest('hex');
return `t=${timestamp},v1=${signature}`;
}
function buildStripeWebhookRequest(harness: ApiTestHarness, eventData: StripeWebhookEventData, signature?: string) {
const {payload, timestamp} = createMockWebhookPayload(eventData);
return createBuilder<{received: boolean}>(harness, '')
.post('/stripe/webhook')
.header('stripe-signature', signature ?? signStripeWebhook(payload, timestamp, Config.stripe.webhookSecret!))
.header('content-type', 'application/json')
.body(payload);
}
export async function sendStripeWebhook(
harness: ApiTestHarness,
eventData: StripeWebhookEventData,
): Promise<{received: boolean}> {
return buildStripeWebhookRequest(harness, eventData).execute();
}
export async function sendStripeWebhookRaw(
harness: ApiTestHarness,
eventData: StripeWebhookEventData,
signature?: string,
): Promise<{response: Response; text: string}> {
return buildStripeWebhookRequest(harness, eventData, signature).executeRaw();
}
export async function sendStripeWebhookExpectStripeError(
harness: ApiTestHarness,
eventData: StripeWebhookEventData,
): Promise<void> {
await buildStripeWebhookRequest(harness, eventData).expect(400, APIErrorCodes.STRIPE_ERROR).execute();
}