Skip to content

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

TypeScript fluxerfluxerapp

feat(billing): gate gifts on account setup, drop card age check

Hampusb21d07eca42f
diff --git a/fluxer_api/src/api/stripe/StripeController.ts b/fluxer_api/src/api/stripe/StripeController.ts
index 739fa0328..d34d52dae 100644
--- a/fluxer_api/src/api/stripe/StripeController.ts
+++ b/fluxer_api/src/api/stripe/StripeController.ts
@@ -14,9 +14,10 @@ import {
} from '@app/api/stripe/BillingConfigCache';
import {mapGiftCodeToMetadataResponse, mapGiftCodeToResponse} from '@app/api/stripe/StripeModel';
import type {HonoApp} from '@app/api/types/HonoEnv';
+import {assertTierAllows, NO_TIER_CONTEXT} from '@app/api/user/AccountTier';
import {lookupGeoip} from '@app/api/utils/IpUtils';
import {Validator} from '@app/api/Validator';
-import {AppNotFoundHandler} from '@fluxer/errors/src/domains/core/ErrorHandlers';
+import {TierGatedActions} from '@fluxer/constants/src/AccountTierConstants';
import {StripeWebhookNotAvailableError} from '@fluxer/errors/src/domains/payment/StripeWebhookNotAvailableError';
import {StripeWebhookSignatureInvalidError} from '@fluxer/errors/src/domains/payment/StripeWebhookSignatureInvalidError';
import {StripeWebhookSignatureMissingError} from '@fluxer/errors/src/domains/payment/StripeWebhookSignatureMissingError';
@@ -206,6 +207,7 @@ export function StripeController(app: HonoApp) {
async (ctx) => {
const {code} = ctx.req.valid('param');
const userId = ctx.get('user').id;
+ assertTierAllows(ctx.get('user'), TierGatedActions.GIFT_REDEEM, NO_TIER_CONTEXT);
await ctx.get('stripeService').gifts.redeemGiftCode(userId, code);
return ctx.body(null, 204);
},
@@ -327,32 +329,6 @@ export function StripeController(app: HonoApp) {
return ctx.json({success: true as const});
},
);
- app.post(
- '/users/@me/age-verification',
- HostedOnlyRoute,
- RateLimitMiddleware(RateLimitConfigs.AGE_VERIFICATION),
- LoginRequired,
- DefaultUserOnly,
- OpenAPI({
- operationId: 'create_age_verification_session',
- summary: 'Create age verification session',
- description:
- 'Creates a Stripe checkout session in setup mode to verify the user holds a credit card for UK adult age verification.',
- responseSchema: UrlResponse,
- statusCode: 200,
- security: ['bearerToken', 'sessionToken'],
- tags: 'Billing',
- }),
- async (ctx) => {
- const ageVerificationService = ctx.get('ageVerificationService');
- if (!ageVerificationService) {
- return AppNotFoundHandler(ctx);
- }
- const userId = ctx.get('user').id;
- const url = await ageVerificationService.createVerificationSession(userId);
- return ctx.json({url});
- },
- );
app.get(
'/premium/refund-eligibility',
HostedOnlyRoute,
diff --git a/fluxer_api/src/api/stripe/services/AgeVerificationService.ts b/fluxer_api/src/api/stripe/services/AgeVerificationService.ts
deleted file mode 100644
index 06cd9fbe9..000000000
--- a/fluxer_api/src/api/stripe/services/AgeVerificationService.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-or-later
-
-import {createUserID, type UserID} from '@app/api/BrandedTypes';
-import {Config} from '@app/api/Config';
-import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
-import {Logger} from '@app/api/Logger';
-import {ensureStripeCustomer} from '@app/api/stripe/StripeCustomer';
-import type {UserRepository} from '@app/api/user/repositories/UserRepository';
-import {dispatchUserUpdate} from '@app/api/user/UserMappers';
-import {UserFlags} from '@fluxer/constants/src/UserConstants';
-import {AgeVerificationAlreadyVerifiedError} from '@fluxer/errors/src/domains/payment/AgeVerificationAlreadyVerifiedError';
-import {StripeError} from '@fluxer/errors/src/domains/payment/StripeError';
-import {StripePaymentNotAvailableError} from '@fluxer/errors/src/domains/payment/StripePaymentNotAvailableError';
-import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';
-import type {ICacheService} from '@pkgs/cache/src/ICacheService';
-import type Stripe from 'stripe';
-
-export class AgeVerificationService {
- constructor(
- private stripe: Stripe | null,
- private userRepository: UserRepository,
- private gatewayService: IGatewayService,
- private cacheService: ICacheService,
- ) {}
-
- async createVerificationSession(userId: UserID): Promise<string> {
- if (!this.stripe) {
- throw new StripePaymentNotAvailableError();
- }
- const user = await this.userRepository.findUnique(userId);
- if (!user) {
- throw new UnknownUserError();
- }
- if (user.flags & UserFlags.AGE_VERIFIED_ADULT) {
- throw new AgeVerificationAlreadyVerifiedError();
- }
- const customerUser = await ensureStripeCustomer({
- stripe: this.stripe,
- user,
- userRepository: this.userRepository,
- cacheService: this.cacheService,
- });
- const customerId = customerUser.stripeCustomerId;
- if (!customerId) {
- throw new StripeError('Stripe customer id missing after customer setup');
- }
- try {
- const session = await this.stripe.checkout.sessions.create({
- customer: customerId,
- client_reference_id: userId.toString(),
- metadata: {
- user_id: userId.toString(),
- verification_type: 'uk_age_verification',
- },
- mode: 'setup',
- payment_method_types: ['card'],
- payment_method_options: {
- card: {
- request_three_d_secure: 'any',
- },
- },
- success_url: `${Config.endpoints.webApp}/age-verification-callback?status=success`,
- cancel_url: `${Config.endpoints.webApp}/age-verification-callback?status=cancel`,
- });
- if (!session.url) {
- Logger.error({userId, sessionId: session.id}, 'Stripe age verification session missing url');
- throw new StripeError('Stripe age verification session missing url');
- }
- Logger.debug({userId, sessionId: session.id}, 'Age verification checkout session created');
- return session.url;
- } catch (error: unknown) {
- if (error instanceof StripeError || error instanceof AgeVerificationAlreadyVerifiedError) {
- throw error;
- }
- Logger.error({error, userId}, 'Failed to create Stripe age verification session');
- const message = error instanceof Error ? error.message : 'Failed to create age verification session';
- throw new StripeError(message);
- }
- }
-
- async completeVerification(session: Stripe.Checkout.Session): Promise<void> {
- if (!this.stripe) {
- throw new StripePaymentNotAvailableError();
- }
- const userId = session.metadata?.user_id;
- if (!userId) {
- Logger.error({sessionId: session.id}, 'Age verification session missing user_id metadata');
- return;
- }
- const setupIntentId = typeof session.setup_intent === 'string' ? session.setup_intent : session.setup_intent?.id;
- if (!setupIntentId) {
- Logger.error({sessionId: session.id, userId}, 'Age verification session missing setup_intent');
- return;
- }
- const setupIntent = await this.stripe.setupIntents.retrieve(setupIntentId, {
- expand: ['payment_method'],
- });
- const paymentMethod = setupIntent.payment_method;
- if (!paymentMethod || typeof paymentMethod === 'string') {
- Logger.error({sessionId: session.id, userId}, 'Could not resolve payment method for age verification');
- return;
- }
- const funding = paymentMethod.card?.funding;
- if (funding !== 'credit') {
- Logger.info({sessionId: session.id, userId, funding}, 'Age verification rejected: card is not a credit card');
- return;
- }
- const parsedUserId = createUserID(BigInt(userId));
- const user = await this.userRepository.findUnique(parsedUserId);
- if (!user) {
- Logger.error({userId}, 'User not found during age verification completion');
- return;
- }
- if (user.flags & UserFlags.AGE_VERIFIED_ADULT) {
- Logger.debug({userId}, 'User already age-verified, skipping flag update');
- return;
- }
- const updatedUser = await this.userRepository.updateFlags(user.id, (flags) => flags | UserFlags.AGE_VERIFIED_ADULT);
- if (!updatedUser) {
- Logger.error({userId}, 'User not found during age verification completion');
- return;
- }
- await dispatchUserUpdate(this.gatewayService, updatedUser);
- Logger.info({userId}, 'Age verification completed successfully');
- }
-}
diff --git a/fluxer_api/src/api/stripe/tests/SelfHostedPremiumRoutes.test.ts b/fluxer_api/src/api/stripe/tests/SelfHostedPremiumRoutes.test.ts
index 655c24f3f..8ba96965f 100644
--- a/fluxer_api/src/api/stripe/tests/SelfHostedPremiumRoutes.test.ts
+++ b/fluxer_api/src/api/stripe/tests/SelfHostedPremiumRoutes.test.ts
@@ -129,8 +129,14 @@ async function readRouteStatus(
path: string,
): Promise<{status: number; code: string | undefined}> {
const builder = token === null ? createBuilderWithoutAuth(harness) : createBuilder(harness, token);
- const request =
- method === 'GET' ? builder.get(path) : method === 'DELETE' ? builder.delete(path) : builder.post(path).body({});
+ let request: typeof builder;
+ if (method === 'GET') {
+ request = builder.get(path);
+ } else if (method === 'DELETE') {
+ request = builder.delete(path);
+ } else {
+ request = builder.post(path).body({});
+ }
const {response, json} = await request.executeRaw();
return {status: response.status, code: (json as {code?: string} | undefined)?.code};
}
@@ -162,7 +168,6 @@ const GIFT_ROUTES: ReadonlyArray<[RouteMethod, string]> = [
];
const HOSTED_ONLY_ROUTES: ReadonlyArray<[RouteMethod, string]> = [
- ['POST', '/users/@me/age-verification'],
['GET', '/premium/refund-eligibility'],
['POST', '/premium/refund-latest'],
['POST', '/premium/switch-to-list-price'],
@@ -193,6 +198,7 @@ describe('self-hosted premium routes', () => {
beforeEach(async () => {
await harness.reset();
+ await getInstanceConfigRepository().setAppPublicConfig({setup: {configured: true}});
setStoredBillingConfig(null);
setCachedInstancePremiumMode('everyone');
});
@@ -436,9 +442,7 @@ describe('hosted premium routes', () => {
test('keeps every Stripe and gift route registered regardless of premium mode', async () => {
setCachedInstancePremiumMode('everyone');
const account = await createTestAccount(harness);
- const routes = [...BILLING_ROUTES, ...GIFT_ROUTES, ...HOSTED_ONLY_ROUTES, ...STORE_BILLING_ROUTES].filter(
- ([, path]) => path !== '/users/@me/age-verification',
- );
+ const routes = [...BILLING_ROUTES, ...GIFT_ROUTES, ...HOSTED_ONLY_ROUTES, ...STORE_BILLING_ROUTES];
for (const [method, path] of routes) {
const result = await readRouteStatus(harness, account.token, method, path);
expect({path, code: result.code}).not.toEqual({path, code: APIErrorCodes.NOT_FOUND});