Skip to content

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

TypeScript fluxerfluxerapp

refactor(billing): narrow exports and flatten billing helpers

Hampusb50844def7f7
diff --git a/fluxer_api/src/api/store_billing/StoreBillingMappers.ts b/fluxer_api/src/api/store_billing/StoreBillingMappers.ts
index 902688131..22131e843 100644
--- a/fluxer_api/src/api/store_billing/StoreBillingMappers.ts
+++ b/fluxer_api/src/api/store_billing/StoreBillingMappers.ts
@@ -3,6 +3,7 @@
import type {StorePurchaseRow} from '@app/api/database/types/StoreBillingTypes';
import {STORE_PRODUCT_SLOTS} from '@app/api/store_billing/StoreBillingConfig';
import {PREMIUM_GRACE_PERIOD_MS} from '@app/api/user/UserHelpers';
+import {toIsoOrNull} from '@fluxer/date_utils/src/DateSerialization';
import type {AdminStorePurchaseResponse} from '@fluxer/schema/src/domains/admin/AdminStoreBillingSchemas';
import type {
PremiumStoreSubscriptionState,
@@ -12,10 +13,6 @@ import type {
const APP_STORE_MANAGE_URL = 'https://apps.apple.com/account/subscriptions';
const GOOGLE_PLAY_MANAGE_URL = 'https://play.google.com/store/account/subscriptions';
-export function toIso(value: Date | null | undefined): string | null {
- return value ? value.toISOString() : null;
-}
-
export function resolveStoreAccessEnd(row: StorePurchaseRow): Date | null {
if (row.state === 'grace' && row.grace_ends_at) {
return row.grace_ends_at;
@@ -64,8 +61,8 @@ export function mapStorePurchaseToResponse(row: StorePurchaseRow): StorePurchase
environment: row.environment,
state: row.state,
entitled: row.entitled,
- expires_at: isSubscription ? toIso(row.expires_at) : null,
- entitled_until: isSubscription && row.entitled ? toIso(resolveStoreAccessEnd(row)) : null,
+ expires_at: isSubscription ? toIsoOrNull(row.expires_at) : null,
+ entitled_until: isSubscription && row.entitled ? toIsoOrNull(resolveStoreAccessEnd(row)) : null,
will_renew: isSubscription ? (row.auto_renew ?? null) : null,
gift_code: row.gift_code ?? null,
created_at: row.created_at.toISOString(),
@@ -88,19 +85,19 @@ export function mapStorePurchaseToAdminResponse(row: StorePurchaseRow): AdminSto
state: row.state,
store_state: row.store_state ?? null,
entitled: row.entitled,
- expires_at: toIso(row.expires_at),
- grace_ends_at: toIso(row.grace_ends_at),
+ expires_at: toIsoOrNull(row.expires_at),
+ grace_ends_at: toIsoOrNull(row.grace_ends_at),
auto_renew: row.auto_renew ?? null,
- started_at: toIso(row.started_at),
- purchased_at: toIso(row.purchased_at),
- revoked_at: toIso(row.revoked_at),
+ started_at: toIsoOrNull(row.started_at),
+ purchased_at: toIsoOrNull(row.purchased_at),
+ revoked_at: toIsoOrNull(row.revoked_at),
revocation_reason: row.revocation_reason ?? null,
superseded: row.superseded_by_store_key != null,
acknowledged: row.acknowledged,
gift_code: row.gift_code ?? null,
- bound_at: toIso(row.bound_at),
- last_event_at: toIso(row.last_event_at),
- synced_at: toIso(row.synced_at),
+ bound_at: toIsoOrNull(row.bound_at),
+ last_event_at: toIsoOrNull(row.last_event_at),
+ synced_at: toIsoOrNull(row.synced_at),
created_at: row.created_at.toISOString(),
updated_at: row.updated_at.toISOString(),
};
@@ -126,7 +123,7 @@ export function mapPremiumStoreSubscriptionState(row: StorePurchaseRow): Premium
billing_cycle: billingCycle,
state: row.state,
expires_at: row.expires_at.toISOString(),
- grace_ends_at: row.state === 'grace' ? toIso(row.grace_ends_at) : null,
+ grace_ends_at: row.state === 'grace' ? toIsoOrNull(row.grace_ends_at) : null,
will_renew: row.auto_renew === true,
manage_url: buildManageUrl(row),
environment: row.environment,
diff --git a/fluxer_api/src/api/store_billing/google_play/GooglePlayAccessTokenProvider.ts b/fluxer_api/src/api/store_billing/google_play/GooglePlayAccessTokenProvider.ts
index 2ca787154..8690371d9 100644
--- a/fluxer_api/src/api/store_billing/google_play/GooglePlayAccessTokenProvider.ts
+++ b/fluxer_api/src/api/store_billing/google_play/GooglePlayAccessTokenProvider.ts
@@ -73,7 +73,7 @@ function configFingerprint(): string {
.digest('hex');
}
-export async function resolveGooglePlayCredentials(): Promise<GooglePlayServiceAccountCredentials> {
+async function resolveGooglePlayCredentials(): Promise<GooglePlayServiceAccountCredentials> {
const cfg = Config.googlePlay;
let serviceAccount: z.infer<typeof ServiceAccountJsonSchema> = {};
if (hasText(cfg.serviceAccountJsonPath)) {
diff --git a/fluxer_api/src/api/store_billing/google_play/GooglePlayPushVerifier.ts b/fluxer_api/src/api/store_billing/google_play/GooglePlayPushVerifier.ts
index 703a7ef6b..959f78507 100644
--- a/fluxer_api/src/api/store_billing/google_play/GooglePlayPushVerifier.ts
+++ b/fluxer_api/src/api/store_billing/google_play/GooglePlayPushVerifier.ts
@@ -6,32 +6,20 @@ import {StoreNotificationUnauthorizedError} from '@fluxer/errors/src/domains/pay
import {createRemoteJWKSet, type JWTPayload, jwtVerify} from 'jose';
import {z} from 'zod';
-export const GOOGLE_OIDC_JWKS_URL = 'https://www.googleapis.com/oauth2/v3/certs';
+const GOOGLE_OIDC_JWKS_URL = 'https://www.googleapis.com/oauth2/v3/certs';
const GOOGLE_OIDC_ISSUERS: Array<string> = ['https://accounts.google.com', 'accounts.google.com'];
const CLOCK_TOLERANCE_SECONDS = 30;
type RemoteJwks = ReturnType<typeof createRemoteJWKSet>;
-export interface GooglePlayPushIdentity {
+interface GooglePlayPushIdentity {
email: string;
subject: string | null;
}
-interface GooglePlayPushVerifierOptions {
- jwksUrl?: string;
- now?: () => Date;
-}
-
export class GooglePlayPushVerifier {
- private readonly jwksUrl: string;
- private readonly now: () => Date;
private jwks: RemoteJwks | null = null;
- constructor(options: GooglePlayPushVerifierOptions = {}) {
- this.jwksUrl = options.jwksUrl ?? GOOGLE_OIDC_JWKS_URL;
- this.now = options.now ?? (() => new Date());
- }
-
async verifyAuthorizationHeader(header: string | null | undefined): Promise<GooglePlayPushIdentity> {
const match = /^Bearer\s+(\S+)$/iu.exec(header?.trim() ?? '');
if (!match) {
@@ -51,7 +39,7 @@ export class GooglePlayPushVerifier {
audience,
requiredClaims: ['exp', 'iat'],
clockTolerance: CLOCK_TOLERANCE_SECONDS,
- currentDate: this.now(),
+ currentDate: new Date(),
});
payload = result.payload;
} catch (error) {
@@ -69,7 +57,7 @@ export class GooglePlayPushVerifier {
private getJwks(): RemoteJwks {
if (!this.jwks) {
- this.jwks = createRemoteJWKSet(new URL(this.jwksUrl));
+ this.jwks = createRemoteJWKSet(new URL(GOOGLE_OIDC_JWKS_URL));
}
return this.jwks;
}
@@ -93,7 +81,7 @@ const PushEnvelopeSchema = z.object({
subscription: z.string().optional(),
});
-export interface GooglePlayPushMessage {
+interface GooglePlayPushMessage {
messageId: string;
data: string;
subscription: string | null;
@@ -200,13 +188,24 @@ function toEvent(notification: z.infer<typeof DeveloperNotificationSchema>): Goo
}
if (notification.voidedPurchaseNotification) {
const voided = notification.voidedPurchaseNotification;
- return {
+ const event: Extract<GooglePlayNotificationEvent, {type: 'voided_purchase'}> = {
type: 'voided_purchase',
purchaseToken: voided.purchaseToken,
orderId: voided.orderId ?? null,
- productType: voided.productType === 1 ? 'subscription' : voided.productType === 2 ? 'one_time' : null,
- refundType: voided.refundType === 1 ? 'full' : voided.refundType === 2 ? 'quantity_based_partial' : null,
+ productType: null,
+ refundType: null,
};
+ if (voided.productType === 1) {
+ event.productType = 'subscription';
+ } else if (voided.productType === 2) {
+ event.productType = 'one_time';
+ }
+ if (voided.refundType === 1) {
+ event.refundType = 'full';
+ } else if (voided.refundType === 2) {
+ event.refundType = 'quantity_based_partial';
+ }
+ return event;
}
if (notification.pendingRefundReviewNotification) {
return {type: 'pending_refund_review', orderId: notification.pendingRefundReviewNotification.orderId ?? null};
@@ -221,7 +220,10 @@ export function decodeGooglePlayDeveloperNotification(data: string): GooglePlayD
let json: unknown;
try {
json = JSON.parse(Buffer.from(data, 'base64').toString('utf8'));
- } catch {
+ } catch (error) {
+ if (!(error instanceof SyntaxError)) {
+ Logger.warn({error}, 'Failed to decode Google Play developer notification');
+ }
return null;
}
const parsed = DeveloperNotificationSchema.safeParse(json);
diff --git a/fluxer_api/src/api/store_billing/tests/GooglePlayPushVerifier.test.ts b/fluxer_api/src/api/store_billing/tests/GooglePlayPushVerifier.test.ts
index de39e4f93..9f8adee83 100644
--- a/fluxer_api/src/api/store_billing/tests/GooglePlayPushVerifier.test.ts
+++ b/fluxer_api/src/api/store_billing/tests/GooglePlayPushVerifier.test.ts
@@ -59,18 +59,6 @@ describe('GooglePlayPushVerifier', () => {
expect(fake.spies.jwksFetches).toBe(1);
});
- it('uses an injected key set URL', async () => {
- const customFake = createGooglePlayDeveloperApiHandlers({jwksUrl: 'https://oidc.fluxer.test/certs'});
- server.use(...customFake.handlers);
- const customVerifier = new GooglePlayPushVerifier({jwksUrl: 'https://oidc.fluxer.test/certs'});
- const token = await customFake.signPushToken();
- await expect(customVerifier.verifyAuthorizationHeader(`Bearer ${token}`)).resolves.toMatchObject({
- email: '[email protected]',
- });
- expect(customFake.spies.jwksFetches).toBe(1);
- expect(fake.spies.jwksFetches).toBe(0);
- });
-
it('rejects a missing or malformed authorization header', async () => {
await expectRejected(undefined);
await expectRejected(null);
@@ -274,6 +262,44 @@ describe('decodeGooglePlayDeveloperNotification', () => {
expect(decode({packageName: 'com.fluxer', somethingNewNotification: {}})?.event).toEqual({type: 'unknown'});
});
+ it.each([
+ {
+ name: 'numeric strings',
+ notification: {purchaseToken: 'strings', productType: '2', refundType: '1'},
+ expected: {
+ type: 'voided_purchase',
+ purchaseToken: 'strings',
+ orderId: null,
+ productType: 'one_time',
+ refundType: 'full',
+ },
+ },
+ {
+ name: 'absent types',
+ notification: {purchaseToken: 'absent'},
+ expected: {
+ type: 'voided_purchase',
+ purchaseToken: 'absent',
+ orderId: null,
+ productType: null,
+ refundType: null,
+ },
+ },
+ {
+ name: 'unknown types',
+ notification: {purchaseToken: 'unknown', productType: 0, refundType: -1},
+ expected: {
+ type: 'voided_purchase',
+ purchaseToken: 'unknown',
+ orderId: null,
+ productType: null,
+ refundType: null,
+ },
+ },
+ ])('decodes voided purchases with $name', ({notification, expected}) => {
+ expect(decode({packageName: 'com.fluxer', voidedPurchaseNotification: notification})?.event).toEqual(expected);
+ });
+
it('returns null for undecodable data', () => {
expect(decodeGooglePlayDeveloperNotification('!!!')).toBeNull();
expect(decodeGooglePlayDeveloperNotification(Buffer.from('not json').toString('base64'))).toBeNull();
diff --git a/fluxer_api/src/api/stripe/services/StripeGiftReversalHandler.ts b/fluxer_api/src/api/stripe/services/StripeGiftReversalHandler.ts
index 1b920285c..23b076160 100644
--- a/fluxer_api/src/api/stripe/services/StripeGiftReversalHandler.ts
+++ b/fluxer_api/src/api/stripe/services/StripeGiftReversalHandler.ts
@@ -18,6 +18,7 @@ import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {clearPerksSanitizedFlag} from '@app/api/user/UserHelpers';
import {dispatchUserUpdate} from '@app/api/user/UserMappers';
import {UserPremiumTypes} from '@fluxer/constants/src/UserConstants';
+import {MS_PER_MINUTE, MS_PER_SECOND} from '@fluxer/date_utils/src/DateConstants';
import {StripeError} from '@fluxer/errors/src/domains/payment/StripeError';
import Stripe from 'stripe';
@@ -33,7 +34,7 @@ interface GiftTrialCut {
premiumUntil: Date;
}
-const MIN_REMAINING_TRIAL_MS = 60_000;
+const MIN_REMAINING_TRIAL_MS = MS_PER_MINUTE;
export class StripeGiftReversalHandler {
constructor(
@@ -304,7 +305,7 @@ export class StripeGiftReversalHandler {
user.premiumGiftExtensionEndsAt?.getTime() ?? 0,
);
const patch: Partial<UserRow> = {
- premium_gift_extension_ends_at: new Date(anchorMs + seconds * 1000),
+ premium_gift_extension_ends_at: new Date(anchorMs + seconds * MS_PER_SECOND),
premium_grace_ends_at: null,
};
if ((user.premiumType ?? 0) <= 0) {
@@ -343,7 +344,7 @@ export class StripeGiftReversalHandler {
if (subscription.status === 'canceled' || subscription.status === 'incomplete_expired') {
return null;
}
- if (!subscription.trial_end || subscription.trial_end * 1000 <= now.getTime()) {
+ if (!subscription.trial_end || subscription.trial_end * MS_PER_SECOND <= now.getTime()) {
return null;
}
const giftSeconds = getGiftTrialSeconds(subscription, giftCode.code);
@@ -351,7 +352,7 @@ export class StripeGiftReversalHandler {
return null;
}
const cutEndMs = Math.max(
- subscription.trial_end * 1000 - giftSeconds * 1000,
+ subscription.trial_end * MS_PER_SECOND - giftSeconds * MS_PER_SECOND,
getGiftTrialPaidUntil(subscription, now.getTime())?.getTime() ?? 0,
);
const endsNow = cutEndMs <= now.getTime() + MIN_REMAINING_TRIAL_MS;
@@ -373,21 +374,24 @@ export class StripeGiftReversalHandler {
throw new StripeError('Stripe client not available for gift trial reversal');
}
const idempotencyKey = `gift_trial_reverse:${redeemer.id}:${giftCode.code}`;
- const subscription = cut.cancel
- ? await stripe.subscriptions.cancel(
- cut.subscriptionId,
- {invoice_now: false, prorate: false, cancellation_details: {comment: 'gift_reversal'}},
- {idempotencyKey},
- )
- : await stripe.subscriptions.update(
- cut.subscriptionId,
- {
- trial_end: cut.trialEnd ? Math.floor(cut.trialEnd.getTime() / 1000) : 'now',
- proration_behavior: 'none',
- metadata: {[getGiftTrialMetadataKey(giftCode.code)]: ''},
- },
- {idempotencyKey},
- );
+ let subscription: Stripe.Subscription;
+ if (cut.cancel) {
+ subscription = await stripe.subscriptions.cancel(
+ cut.subscriptionId,
+ {invoice_now: false, prorate: false, cancellation_details: {comment: 'gift_reversal'}},
+ {idempotencyKey},
+ );
+ } else {
+ subscription = await stripe.subscriptions.update(
+ cut.subscriptionId,
+ {
+ trial_end: cut.trialEnd ? Math.floor(cut.trialEnd.getTime() / MS_PER_SECOND) : 'now',
+ proration_behavior: 'none',
+ metadata: {[getGiftTrialMetadataKey(giftCode.code)]: ''},
+ },
+ {idempotencyKey},
+ );
+ }
await mirrorSubscription(
subscription,
redeemer.id,
@@ -460,10 +464,10 @@ export class StripeGiftReversalHandler {
redeemer.premiumGiftExtensionEndsAt?.getTime() ?? 0,
);
const afterMs = Math.max(nowMs, nextUntil?.getTime() ?? 0, nextGiftEnd?.getTime() ?? 0);
- return Math.max(0, Math.ceil((beforeMs - afterMs) / 1000));
+ return Math.max(0, Math.ceil((beforeMs - afterMs) / MS_PER_SECOND));
}
- computeRemainingGiftEntitlement(
+ private computeRemainingGiftEntitlement(
redeemedGifts: Array<GiftCode>,
excludedCode: string | null,
): RemainingGiftEntitlement {
diff --git a/fluxer_api/src/api/stripe/services/StripeSubscriptionReconciler.ts b/fluxer_api/src/api/stripe/services/StripeSubscriptionReconciler.ts
index 384221b1c..6cb82e6cf 100644
--- a/fluxer_api/src/api/stripe/services/StripeSubscriptionReconciler.ts
+++ b/fluxer_api/src/api/stripe/services/StripeSubscriptionReconciler.ts
@@ -251,7 +251,7 @@ export class StripeSubscriptionReconciler {
return false;
}
- getPriceIdFromInvoice(invoice: Stripe.Invoice): string | null {
+ private getPriceIdFromInvoice(invoice: Stripe.Invoice): string | null {
if (!invoice.lines?.data?.length) {
return null;
}